Java Reference
In-Depth Information
will throw an exception. The encodings UnicodeBigUnmarked and UnicodeLittleUnmarked
(supported in JDK as of 1.3) omit the byte-order marker, so they are suitable for use with
Framer.nextToken() .
Framer.java
0 import java.io.*; // for InputStream and ByteArrayOutputStream
1
2 public class Framer {
3
4
public static byte[] nextToken(InputStream in, byte[] delimiter)
5
throws IOException {
6
int nextByte;
7
8
// If the stream has already ended, return null
9
if ((nextByte = in.read()) == −1)
10
return null;
11
12
ByteArrayOutputStream tokenBuffer = new ByteArrayOutputStream();
13
do {
14
tokenBuffer.write(nextByte);
15
byte[] currentToken = tokenBuffer.toByteArray();
16
if (endsWith(currentToken, delimiter)) {
17
int tokenLength = currentToken.length − delimiter.length;
18
byte[] token = new byte[tokenLength];
19
System.arraycopy(currentToken, 0, token, 0, tokenLength);
20
return token;
21
}
22
} while ((nextByte = in.read()) != −1);
// Stop on end−of−stream
23
return tokenBuffer.toByteArray();
// Received at least 1 byte
24
}
25
26
// Returns true if value ends with the bytes in suffix
27
private static boolean endsWith(byte[] value, byte[] suffix) {
28
if (value.length < suffix.length)
29
return false;
30
31
for (int offset = 1; offset <= suffix.length; offset++)
32
if (value[value.length − offset] != suffix[suffix.length − offset])
33
return false;
34
return true;
35
}
36 }
Framer.java
 
Search WWH ::




Custom Search