1 /*
2 * Copyright �, Aegeus Technology Limited.
3 * All rights reserved.
4 */
5 package jsdsi.util;
6
7 import java.io.BufferedInputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.util.Iterator;
11
12 import jsdsi.JsdsiRuntimeException;
13
14
15 /***
16 * Adaptor class to make an InputStream function as an Iterator.
17 *
18 * @author Sean Radford
19 * @version $Revision: 1.4 $ $Date: 2004/06/09 16:34:41 $
20 */
21 public class InputStreamIterator implements Iterator {
22
23 /***
24 * The stream to iterate over
25 */
26 private InputStream is = null;
27
28 /***
29 * The bufferSize to use. Defaults to 128 bytes.
30 */
31 private int bufSize = 128;
32
33 /***
34 *
35 */
36 public InputStreamIterator(InputStream is) {
37 super();
38 // make sure the input stream supports marks
39 if (is.markSupported()) {
40 this.is = is;
41 } else {
42 this.is = new BufferedInputStream(is);
43 }
44 }
45
46 /***
47 *
48 * @param is the InputStream to iterate over
49 * @param bufSize the buffer size to return
50 */
51 public InputStreamIterator(InputStream is, int bufSize) {
52 this(is);
53 this.bufSize = bufSize;
54 }
55
56 /***
57 * Not supported by this implementation.
58 * @throws UnsupportedOperationException as not supported by this implementation
59 * @see java.util.Iterator#remove()
60 */
61 public void remove() {
62 if (true)
63 throw new UnsupportedOperationException("Remove method is not supported by this Iterator");
64 }
65
66 /***
67 * @see java.util.Iterator#hasNext()
68 * @throws JsdsiRuntimeException wrapping any IOException
69 */
70 public boolean hasNext() {
71 int i;
72 try {
73 this.is.mark(1);
74 i = this.is.read();
75 this.is.reset();
76 } catch (IOException e) {
77 throw new JsdsiRuntimeException("Error reading from InputStream",
78 e);
79 }
80 return i<0 ? false: true;
81 }
82
83 /***
84 * Returns the a number of bytes as a <code>byte[]</code> from the input stream
85 * (up to <code>bufSize</code> in length), or <code>null</code> if the end of the
86 * stream has been reached.
87 * @see java.util.Iterator#next()
88 * @throws JsdsiRuntimeException wrapping any IOException
89 */
90 public Object next() {
91 byte[] bytes = new byte[this.bufSize];
92 int len = -1;
93 try {
94 len = this.is.read(bytes);
95 } catch (IOException e) {
96 throw new JsdsiRuntimeException("Error reading from InputStream",
97 e);
98 }
99 if (len==-1) {
100 return null;
101 } else if (len==this.bufSize) {
102 return bytes;
103 } else {
104 byte[] toReturn = new byte[len];
105 System.arraycopy(bytes, 0, toReturn, 0, len);
106 return toReturn;
107 }
108 }
109
110 /***
111 * @return the bufSize
112 */
113 public int getBufSize() {
114 return bufSize;
115 }
116
117 }
This page was automatically generated by Maven