Why use ByteArrayInputStream rather than byte [] in Java

As I understand it, it is ByteArrayInputStreamused to read data byte[]. Why should I use it, and not just byte[](for example, after reading it from the database).

What is the difference between the two?

+4
source share
2 answers

If the input is always equal byte[], then you are right, often there is no need for a stream. And if you do not need it, do not use it . Another advantage of ByteArrayInputStream is that it serves as a very strong sign that you plan to use read-only bytes (since the stream does not provide an interface for changing them), although it is important to note that the programmer can often still directly access bytes therefore you should not use this in a situation where a security issue is a problem.

byte[], , .., - " ", , . , InputStream. , ByteArrayInputStream - InputStream .

, , :

  • , - ( , , ). byte[] . , , InputStream - , byte[], ByteArrayInputStream.
  • , . unit test ; . , InputStream, ByteArrayInputStream.
+4
  • ByteArrayInputStream , , . , .
  • ByteArrayInputStream ,
  • , , .
  • , , , .

  • byte[], ,

    byte data[] = { 65, 66, 67, 68, 69 }; // data
        for (int index = 0; index < data.length; index++) {
            System.out.print((char) data[index] + "   ");
        }
        int c = 0;
        ByteArrayInputStream bInput = new ByteArrayInputStream(data);
        while ((bInput.read()) != -1) {
            System.out.println(Character.toUpperCase((char) c));
        }
    
+3

Source: https://habr.com/ru/post/1617007/


All Articles