01: /*
02: * Copyright (C) 2005-2006 data2c GmbH (www.data2c.com)
03: *
04: * Authors:
05: * Wolfgang S. Kechel - wolfgang.kechel@data2c.com
06: *
07: * Licensed under the Apache License, Version 2.0 (the "License");
08: * you may not use this file except in compliance with the License.
09: * You may obtain a copy of the License at
10: *
11: * http://www.apache.org/licenses/LICENSE-2.0
12: *
13: * Unless required by applicable law or agreed to in writing, software
14: * distributed under the License is distributed on an "AS IS" BASIS,
15: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16: * See the License for the specific language governing permissions and
17: * limitations under the License.
18: */
19:
20: package org.hecl.rms;
21:
22: import java.io.OutputStream;
23: import java.io.IOException;
24:
25: import javax.microedition.rms.RecordEnumeration;
26: import javax.microedition.rms.RecordStore;
27: import javax.microedition.rms.RecordStoreException;
28:
29: public class RMSOutputStream extends OutputStream {
30: public RMSOutputStream(String storename) throws IOException {
31: super ();
32: rsname = storename;
33:
34: try {
35: rs = RecordStore.openRecordStore(rsname, true);
36: // clear up any old content!
37: RecordEnumeration records = rs.enumerateRecords(null, null,
38: false);
39: while (records.hasNextElement()) {
40: rs.deleteRecord(records.nextRecordId());
41: }
42: records.destroy();
43: } catch (Exception e) {
44: throw new IOException(e.toString());
45: }
46: }
47:
48: public void close() throws IOException {
49: if (rs != null) {
50: flush();
51: try {
52: rs.closeRecordStore();
53: } catch (Exception e) {
54: } finally {
55: rs = null;
56: buf = null;
57: }
58: super .close();
59: }
60: //System.err.println("RMSOutputStream closed, written="+nwritten);
61: }
62:
63: public void flush() throws IOException {
64: if (rs != null && bufferpos > 0) {
65: try {
66: rs.addRecord(buf, 0, bufferpos);
67: nwritten += bufferpos;
68: }
69: //RecordStoreNotOpenException
70: //RecordStoreException
71: //RecordStoreFullException
72: //SecurityException
73: catch (Exception e) {
74: throw new IOException(e.toString());
75: }
76: bufferpos = 0;
77: }
78: }
79:
80: public void write(int b) throws IOException {
81: if (rs == null)
82: throw new IOException("stream closed.");
83: buf[bufferpos++] = (byte) (b & 0xff);
84: if (bufferpos >= BUFSIZE) {
85: flush();
86: }
87:
88: }
89:
90: private static final int BUFSIZE = 1024;
91:
92: private String rsname;
93: private RecordStore rs;
94: private int bufferpos = 0;
95: private int nwritten = 0;
96: private byte[] buf = new byte[BUFSIZE];
97: }
|