Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 919
Simon Lenz Avatar asked Aug 24 '10 07:08

Simon Lenz


People also ask

How do you copy byte array?

copyOf(byte[] original, int newLength) method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.

What is byte array stream?

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method. Closing a ByteArrayInputStream has no effect.

What is a byte stream?

A bytestream is a sequence of bytes. Typically, each byte is an 8-bit quantity, and so the term octet stream is sometimes used interchangeably. An octet may be encoded as a sequence of 8 bits in multiple different ways (see bit numbering) so there is no unique and direct translation between bytestreams and bitstreams.

What is byte stream in Java?

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file −


1 Answers

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);
like image 131
user207421 Avatar answered Oct 08 '22 11:10

user207421