1
2
3
4
5
6
7
8
9
10
11
12
13 package org.abstracthorizon.mercury.common.io;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.ByteArrayOutputStream;
17 import java.io.File;
18 import java.io.FileInputStream;
19 import java.io.FileOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23
24
25
26
27
28
29
30 public class TempStorage {
31
32
33 public static final int MAX_MEMORY = 102400;
34
35
36 protected int maxMemory = MAX_MEMORY;
37
38
39 protected File file = null;
40
41
42 protected OutputStream defaultOutputStream = new OutputStreamImpl();
43
44
45 protected OutputStream os = null;
46
47
48 protected ByteArrayOutputStream buffer = new ByteArrayOutputStream(MAX_MEMORY);
49
50
51 protected int size = 0;
52
53
54 protected String prefix = "tmp";
55
56
57 protected String suffix = ".tmp";
58
59
60
61
62 public TempStorage() {
63 }
64
65
66
67
68
69
70 public TempStorage(String prefix, String suffix) {
71 this.prefix = prefix;
72 this.suffix = suffix;
73 }
74
75
76
77
78
79
80
81 public TempStorage(String prefix, String suffix, int maxMemory) {
82 this(prefix, suffix);
83 this.maxMemory = maxMemory;
84 }
85
86
87
88
89
90 public File getFile() {
91 return file;
92 }
93
94
95
96
97
98 public int getSize() {
99 return size;
100 }
101
102
103
104
105
106 public OutputStream getOutputStream() {
107 return defaultOutputStream;
108 }
109
110
111
112
113
114
115 public InputStream getInputStream() throws IOException {
116 if (file != null) {
117 return new FileInputStream(file);
118 } else {
119 return new ByteArrayInputStream(buffer.toByteArray());
120 }
121 }
122
123
124
125
126
127 public void clear() throws IOException {
128 if (file != null) {
129 file.delete();
130 os.close();
131 }
132 buffer = new ByteArrayOutputStream(MAX_MEMORY);
133 size = 0;
134 }
135
136
137
138
139
140
141 protected class OutputStreamImpl extends OutputStream {
142
143 @Override
144 public void write(int b) throws IOException {
145 byte[] bs = new byte[1];
146 bs[0] = (byte)b;
147 write(bs);
148 }
149
150 @Override
151 public void write(byte b[]) throws IOException {
152 write(b, 0, b.length);
153 }
154
155 @Override
156 public void write(byte[] b, int off, int len) throws IOException {
157 if (file != null) {
158 os.write(b, off, len);
159 } else {
160 if (size + b.length > MAX_MEMORY) {
161 file = File.createTempFile(prefix, suffix);
162 file.deleteOnExit();
163 os = new FileOutputStream(file);
164 os.write(buffer.toByteArray());
165 os.write(b, off, len);
166 buffer = null;
167 } else {
168 buffer.write(b, off, len);
169 }
170 }
171 size = size + len;
172 }
173 }
174 }