views:

83

answers:

2

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 ByteArrayOutputStream();
    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

+5  A: 

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);
EJP
+4  A: 

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:

while((int 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.

musiKk
Thanks very much! i understand what was the problem:)(because i used the read method two times it jumps two times)
CaptnLenz