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.fs;
07:
08: import java.io.EOFException;
09: import java.io.IOException;
10:
11: /**
12: * In this file system, files are kept fully in memory until stored.
13: */
14: public class FileObjectDatabase implements FileObject {
15:
16: private FileSystemDatabase db;
17: private String fileName;
18: private byte[] data;
19: private int pos, length;
20: private boolean changed;
21:
22: FileObjectDatabase(FileSystemDatabase db, String fileName,
23: byte[] data, boolean changed) {
24: this .db = db;
25: this .fileName = fileName;
26: this .data = data;
27: this .length = data.length;
28: this .changed = changed;
29: }
30:
31: public void close() throws IOException {
32: sync();
33: }
34:
35: public long getFilePointer() throws IOException {
36: return pos;
37: }
38:
39: public long length() throws IOException {
40: return length;
41: }
42:
43: public void readFully(byte[] b, int off, int len)
44: throws IOException {
45: if (pos + len > length) {
46: throw new EOFException();
47: }
48: System.arraycopy(data, pos, b, off, len);
49: pos += len;
50: }
51:
52: public void seek(long pos) throws IOException {
53: this .pos = (int) pos;
54: }
55:
56: public void setFileLength(long newLength) throws IOException {
57: this .length = (int) newLength;
58: if (length != data.length) {
59: byte[] n = new byte[length];
60: System.arraycopy(data, 0, n, 0, Math.min(data.length,
61: n.length));
62: data = n;
63: changed = true;
64: }
65: pos = Math.min(pos, length);
66: }
67:
68: public void sync() throws IOException {
69: if (changed) {
70: db.write(fileName, data, length);
71: changed = false;
72: }
73: }
74:
75: public void write(byte[] b, int off, int len) throws IOException {
76: if (pos + len > data.length) {
77: int newLen = Math.max(data.length * 2, pos + len);
78: byte[] n = new byte[newLen];
79: System.arraycopy(data, 0, n, 0, length);
80: data = n;
81: }
82: System.arraycopy(b, off, data, pos, len);
83: pos += len;
84: length = Math.max(length, pos);
85: changed = true;
86: }
87:
88: }
|