1 package tim.prune.save.xml;
3 import java.nio.charset.Charset;
6 * Class to collect the bytes from an input stream
7 * and turn them into a String
9 public class ByteBuffer
12 private byte[] _bytes = new byte[1024];
13 // Current position to append
14 private int _currPos = 0;
15 // Flag for recognising utf8 encoded streams
16 private boolean _streamUtf8 = false;
17 // Flag for whether system is utf8 or not
18 private final boolean _systemUtf8 = XmlUtils.isSystemUtf8();
21 * Append the given byte to the buffer
22 * @param inB byte to append
24 public void appendByte(byte inB)
26 // Resize array if necessary
27 if (_currPos >= _bytes.length)
29 byte[] bigger = new byte[_bytes.length * 2];
30 System.arraycopy(_bytes, 0, bigger, 0, _bytes.length);
33 // Append byte and increment counter
34 _bytes[_currPos] = inB;
39 * Clear the buffer and reset
44 // Reduce size back to default if it's got too big
45 if (_bytes.length > 5000) {
46 _bytes = new byte[1024];
51 * Set the flag that this stream is encoded with utf8
53 public void setEncodingUtf8() {
58 * @return contents of buffer as a String
60 public String toString()
62 // Sometimes the encoding of the read file isn't the default encoding of the system
63 if (_streamUtf8 && !_systemUtf8)
65 return new String(_bytes, 0, _currPos, Charset.forName("UTF-8"));
67 // Otherwise just use system encoding
68 return new String(_bytes, 0, _currPos);
72 * Look for the given character sequence in the last characters read
73 * @param inChars sequence to look for
74 * @return true if sequence found
76 public boolean foundSequence(char[] inChars)
78 final int numChars = inChars.length;
79 if (_currPos < numChars) {return false;}
80 for (int i=0; i<numChars; i++)
82 char searchChar = inChars[numChars - 1 - i];
83 char sourceChar = (char) _bytes[_currPos - 1 - i];
84 if (searchChar != sourceChar) {return false;}