copy a stream via byte[]
Hiho,
i have to copy an inputstream. And after a bit of searching in the net, i tried this with the help of a bytearray. My code looks like this("is" is the inputstream):
ByteArrayOutputStream bos = new ByteArrayOutputSt开发者_JS百科ream();
while (is.read() != -1) {
bos.write(is.read());
}
byte[] ba = bos.toByteArray();
InputStream test = new ByteArrayInputStream(ba);
InputStream test2 = new ByteArrayInputStream(ba);
And it works.. nearly
In both the stream, the programm copied only every second character So "DOR A="104"/>" in the "is"-stream becomes: "O =14/" in the other streams
What is the Problem? i can not understand what is going on.
Hope anybody could give me the solution:)
greetings
That's because you ignored all the odd characters unless they were -1, by calling read() twice in your loop. Here's the correct way using a buffer (you can tune the buffer size):
int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count);
You have to assign the read byte in the while
loop to a variable. In your current code you just discard it. The following is correct:
int b;
while((b = read()) != -1) {
bos.write(b);
}
Of course reading single bytes is not very efficient. You should consider using byte arrays in your next version.
精彩评论