1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.store; |
7 | |
8 | import java.io.OutputStream; |
9 | import org.h2.engine.Constants; |
10 | import org.h2.tools.CompressTool; |
11 | |
12 | /** |
13 | * An output stream that is backed by a file store. |
14 | */ |
15 | public class FileStoreOutputStream extends OutputStream { |
16 | private FileStore store; |
17 | private final Data page; |
18 | private final String compressionAlgorithm; |
19 | private final CompressTool compress; |
20 | private final byte[] buffer = { 0 }; |
21 | |
22 | public FileStoreOutputStream(FileStore store, DataHandler handler, |
23 | String compressionAlgorithm) { |
24 | this.store = store; |
25 | if (compressionAlgorithm != null) { |
26 | this.compress = CompressTool.getInstance(); |
27 | this.compressionAlgorithm = compressionAlgorithm; |
28 | } else { |
29 | this.compress = null; |
30 | this.compressionAlgorithm = null; |
31 | } |
32 | page = Data.create(handler, Constants.FILE_BLOCK_SIZE); |
33 | } |
34 | |
35 | @Override |
36 | public void write(int b) { |
37 | buffer[0] = (byte) b; |
38 | write(buffer); |
39 | } |
40 | |
41 | @Override |
42 | public void write(byte[] buff) { |
43 | write(buff, 0, buff.length); |
44 | } |
45 | |
46 | @Override |
47 | public void write(byte[] buff, int off, int len) { |
48 | if (len > 0) { |
49 | page.reset(); |
50 | if (compress != null) { |
51 | if (off != 0 || len != buff.length) { |
52 | byte[] b2 = new byte[len]; |
53 | System.arraycopy(buff, off, b2, 0, len); |
54 | buff = b2; |
55 | off = 0; |
56 | } |
57 | int uncompressed = len; |
58 | buff = compress.compress(buff, compressionAlgorithm); |
59 | len = buff.length; |
60 | page.checkCapacity(2 * Data.LENGTH_INT + len); |
61 | page.writeInt(len); |
62 | page.writeInt(uncompressed); |
63 | page.write(buff, off, len); |
64 | } else { |
65 | page.checkCapacity(Data.LENGTH_INT + len); |
66 | page.writeInt(len); |
67 | page.write(buff, off, len); |
68 | } |
69 | page.fillAligned(); |
70 | store.write(page.getBytes(), 0, page.length()); |
71 | } |
72 | } |
73 | |
74 | @Override |
75 | public void close() { |
76 | if (store != null) { |
77 | try { |
78 | store.close(); |
79 | } finally { |
80 | store = null; |
81 | } |
82 | } |
83 | } |
84 | |
85 | } |