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
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.
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.
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.
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 −
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With