1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.javadpkg.io.impl;
20
21 import java.io.File;
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.InputStream;
25
26 import net.sourceforge.javadpkg.io.DataSource;
27 import net.sourceforge.javadpkg.io.Streams;
28
29
30
31
32
33
34
35
36
37 public class DataFileSource implements DataSource {
38
39
40
41 private File file;
42
43 private boolean resettable;
44
45 private String name;
46
47 private InputStream in;
48
49
50
51
52
53
54 private UncloseableInputStream publicIn;
55
56 private boolean opened;
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75 public DataFileSource(File file, boolean resettable) {
76 super();
77
78 if (file == null)
79 throw new IllegalArgumentException("Argument file is null.");
80
81 this.file = file;
82 this.name = file.getAbsolutePath();
83 this.in = null;
84 this.publicIn = null;
85 this.opened = false;
86 this.resettable = resettable;
87 }
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107 public DataFileSource(File file) {
108 this(file, true);
109 }
110
111
112 @Override
113 public String getName() {
114 return this.name;
115 }
116
117
118 @Override
119 public long getLength() {
120 return this.file.length();
121 }
122
123
124 @Override
125 public boolean isResettable() {
126 return this.resettable;
127 }
128
129
130 @Override
131 public void reset() throws IOException {
132 if (!this.resettable)
133 throw new IOException("Source |" + this.name + "| doesn't support a reset.");
134 try {
135 if (this.in != null) {
136 this.in.close();
137 }
138 } finally {
139 this.in = null;
140 this.publicIn = null;
141 this.opened = false;
142 }
143 }
144
145
146
147
148
149
150
151
152 private void createPublicInputStream() {
153 this.publicIn = new UncloseableInputStream(this.in, new DelegateCloseHandler(this));
154 }
155
156
157
158
159
160
161
162
163
164
165
166 private void ensureInputStream() throws IOException {
167 if (this.in == null) {
168 if (!this.opened) {
169 try {
170 this.in = Streams.createBufferedFileInputStream(this.file);
171 } catch (FileNotFoundException e) {
172 throw new IOException("Couldn't open stream on source |" + this.name + "|: " + e.getMessage());
173 }
174 this.createPublicInputStream();
175 } else
176 throw new IOException("The stream of source |" + this.name + "| is already closed.");
177 }
178 }
179
180
181 @Override
182 public InputStream getInputStream() throws IOException {
183 this.ensureInputStream();
184 return this.publicIn;
185 }
186
187
188 @Override
189 public void close() throws IOException {
190 try {
191 if (this.in != null) {
192 this.in.close();
193 }
194 } finally {
195 this.publicIn = null;
196 this.in = null;
197 }
198 }
199
200
201 }