File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\store\FileStoreOutputStream.java.html

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