1

The Documentation on ByteArrayInputStream says :

java.io.ByteArrayInputStream.ByteArrayInputStream(byte[] buf) Creates a ByteArrayInputStream so that it uses buf as its buffer array. The buffer array is not copied. The initial value of pos is 0 and the initial value of count is the length of buf. Parameters: buf the input buffer.

When I run the below code ,

        byte[] b = new byte[10];
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    String someText = "Java byte arrayinput stream test - this string will be used.";
    b = someText.getBytes();

    int c =0;
    while( ( c = bais.read()) != -1 ){
        System.out.print((char)c);
    }

the output I get is based on the 10 byte blank array, not the string used to test. This indicates that the constructor of ByteArrayInputStream must be copying the byte array rather than storing a reference to the passed byte array.This contradicts the documentation. Can anyone clarify my understanding , if the byte array is copied or not ?( and if it is not copied , then why the output does not reflect the state of byte array b ?

Bhaskar
  • 7,443
  • 5
  • 39
  • 51
  • Look at line 4 and you see what is wrong with your argument. What, exactly, does b = someText.getBytes() do? – Ingo Apr 05 '11 at 12:52
  • I realize it .., I can only be shocked at how naive I was asking the question after reading all the answers ! – Bhaskar Apr 05 '11 at 13:00

3 Answers3

6

The problem is with your assignment statement. The array in the input stream is the same as the one declared:

byte[] b = new byte[10];

However when you use String's getBytes() you are creating a new array and assigning its value to b. Essentially what you have done is this:

byte[] tmp = someText.getBytes();  //get bytes creates a new array
b = tmp;

For the results you want to see, what you need to do is get the byte data, and then copy it into your original array:

byte[] tmp = someText.getBytes();
for(int i=0;i < Math.min(tmp.length, b.length);i++) {
  b[i] = tmp[i];
}

this will produce the behavior you expect.

M. Jessup
  • 8,153
  • 1
  • 29
  • 29
2

You're not modifying the byte[] initially allocated in the first line.

Instead you're simply re-assigning b to point to a new byte[].

Try this instead:

b[0] = 'H';
b[1] = 'e';
b[2] = 'l';
b[3] = 'l';
b[4] = 'o';
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
2

You misunderstand how Java variables work.

This statement creates a new byte[] and assigns it to the variable b:

byte[] b = new byte[10];

This statement creates another new byte[], and also assigns it to the variable b, replacing the former contents of that variable:

b = someText.getBytes();

You pass the original value stored in b to the ByteArrayInputStream constructor. Internally, the stream has its own variable, which is assigned a value by the constructor. Afterwards, you change the program's variable, but doing so does not change the stream's variable.

Anon
  • 2,328
  • 12
  • 7