01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.store;
07:
08: import java.io.IOException;
09: import java.io.OutputStream;
10: import java.sql.SQLException;
11:
12: import org.h2.engine.Constants;
13: import org.h2.message.Message;
14: import org.h2.tools.CompressTool;
15:
16: /**
17: * An output stream that is backed by a file store.
18: */
19: public class FileStoreOutputStream extends OutputStream {
20: private FileStore store;
21: private DataPage page;
22: private String compressionAlgorithm;
23: private CompressTool compress;
24:
25: public FileStoreOutputStream(FileStore store, DataHandler handler,
26: String compressionAlgorithm) {
27: this .store = store;
28: if (compressionAlgorithm != null) {
29: compress = CompressTool.getInstance();
30: this .compressionAlgorithm = compressionAlgorithm;
31: }
32: page = DataPage.create(handler, Constants.FILE_BLOCK_SIZE);
33: }
34:
35: public void write(byte[] buff) throws IOException {
36: write(buff, 0, buff.length);
37: }
38:
39: public void write(byte[] buff, int off, int len) throws IOException {
40: if (len > 0) {
41: try {
42: page.reset();
43: if (compress != null) {
44: if (off != 0 || len != buff.length) {
45: byte[] b2 = new byte[len];
46: System.arraycopy(buff, off, b2, 0, len);
47: buff = b2;
48: off = 0;
49: }
50: int uncompressed = len;
51: buff = compress
52: .compress(buff, compressionAlgorithm);
53: len = buff.length;
54: page.writeInt(len);
55: page.writeInt(uncompressed);
56: page.write(buff, off, len);
57: } else {
58: page.writeInt(len);
59: page.write(buff, off, len);
60: }
61: page.fillAligned();
62: store.write(page.getBytes(), 0, page.length());
63: } catch (SQLException e) {
64: throw Message.convertToIOException(e);
65: }
66: }
67: }
68:
69: public void close() throws IOException {
70: if (store != null) {
71: try {
72: store.close();
73: } finally {
74: store = null;
75: }
76: }
77: }
78:
79: public void write(int b) throws IOException {
80: throw new IOException("this method is not implemented");
81: }
82:
83: }
|