1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.morph.util;
17
18 import java.io.InputStream;
19 import java.io.BufferedInputStream;
20 import java.io.IOException;
21
22 import org.springframework.core.io.Resource;
23
24 /**
25 * Special <code>InputStream</code> that will concatenate the contents of a Spring Resource[].
26 * Adapted from Apache Ant ConcatResourceInputStream.
27 */
28 public class ResourceArrayInputStream extends InputStream {
29
30 private static final int EOF = -1;
31 private boolean eof = false;
32 private InputStream currentStream;
33 private Resource[] resources;
34 private int index = -1;
35
36 /**
37 * Construct a new ResourceArrayInputStream.
38 * @param resources
39 */
40 public ResourceArrayInputStream(Resource[] resources) {
41 this.resources = resources;
42 }
43
44 /**
45 * Close the stream.
46 * @throws IOException if there is an error.
47 */
48 public void close() throws IOException {
49 closeCurrent();
50 eof = true;
51 }
52
53 /**
54 * Read a byte.
55 * @return the byte (0 - 255) or -1 if this is the end of the stream.
56 * @throws IOException if there is an error.
57 */
58 public int read() throws IOException {
59 if (eof) {
60 return EOF;
61 }
62 int result = readCurrent();
63 if (result == EOF) {
64 nextResource();
65 result = readCurrent();
66 }
67 return result;
68 }
69
70 private int readCurrent() throws IOException {
71 return eof || currentStream == null ? EOF : currentStream.read();
72 }
73
74 private void nextResource() throws IOException {
75 closeCurrent();
76 if (resources == null || ++index == resources.length) {
77 eof = true;
78 } else {
79 currentStream = new BufferedInputStream(resources[index].getInputStream());
80 }
81 }
82
83 private void closeCurrent() {
84 if (currentStream != null) {
85 try {
86 currentStream.close();
87 } catch (IOException e) {
88
89 }
90 currentStream = null;
91 }
92 }
93 }