KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > store > FileStoreOutputStream


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.store;
6
7 import java.io.IOException JavaDoc;
8 import java.io.OutputStream JavaDoc;
9 import java.sql.SQLException JavaDoc;
10
11 import org.h2.engine.Constants;
12 import org.h2.message.Message;
13 import org.h2.tools.CompressTool;
14
15 public class FileStoreOutputStream extends OutputStream JavaDoc {
16     private FileStore store;
17     private DataPage page;
18     private String JavaDoc compressionAlgorithm;
19     private CompressTool compress;
20     
21     public FileStoreOutputStream(FileStore store, DataHandler handler, String JavaDoc compressionAlgorithm) {
22         this.store = store;
23         if(compressionAlgorithm != null) {
24             compress = CompressTool.getInstance();
25             this.compressionAlgorithm = compressionAlgorithm;
26         }
27         page = DataPage.create(handler, Constants.FILE_BLOCK_SIZE);
28     }
29
30     public void write(byte[] buff) throws IOException JavaDoc {
31         write(buff, 0, buff.length);
32     }
33     
34     public void write(byte[] buff, int off, int len) throws IOException JavaDoc {
35         if(len > 0) {
36             try {
37                 page.reset();
38                 if(compress != null) {
39                     if(off != 0 || len != buff.length) {
40                         byte[] b2 = new byte[len];
41                         System.arraycopy(buff, off, b2, 0, len);
42                         buff = b2;
43                         off = 0;
44                     }
45                     int uncompressed = len;
46                     buff = compress.compress(buff, compressionAlgorithm);
47                     len = buff.length;
48                     page.writeInt(len);
49                     page.writeInt(uncompressed);
50                     page.write(buff, off, len);
51                 } else {
52                     page.writeInt(len);
53                     page.write(buff, off, len);
54                 }
55                 page.fillAligned();
56                 store.write(page.getBytes(), 0, page.length());
57             } catch(SQLException JavaDoc e) {
58                 throw Message.convertToIOException(e);
59             }
60         }
61     }
62     
63     public void close() throws IOException JavaDoc {
64         if(store != null) {
65             try {
66                 store.close();
67             } finally {
68                 store = null;
69             }
70         }
71     }
72     
73     public void write(int b) throws IOException JavaDoc {
74         throw new IOException JavaDoc("this method is not implemented");
75     }
76     
77 }
78
Popular Tags