Search code examples
javaarraysdatainputstream

How to read an array of bytes from a file using datainput stream, and print the array of bytes in java


I have stored an array of bytes byte[] testByte; testByte = new byte[]{3,4} into a file, now I need to read from the file and assign the array of bytes to a variable and print it.

I have done the following code,but i am not able to print the array of bytes

public static void main(String[] args) throws IOException {

  InputStream is = null;
  DataInputStream dis = null;

  try{
     // create input stream from file input stream
     is = new FileInputStream("c:\\test.txt");

     // create data input stream
     dis = new DataInputStream(is);

     // count the available bytes form the input stream
     int count = is.available();

     // create buffer
     byte[] bs = new byte[count];

     // read data into buffer
     dis.read(bs);

              }

Now how to store the contents in the buffer bs into an array.

Please help to resolve this


Solution

  • You can store the content of bs buffer using new String

    public static void main(String[] args) throws IOException {
    
          InputStream is = null;
          DataInputStream dis = null;
          int count = 0;
          byte[] bs = null;
          String content = "";
    
          try{
    
             is = new FileInputStream("C:\\test.txt");
    
             dis = new DataInputStream(is);
    
             count = is.available();
    
             bs = new byte[count];
    
             dis.read(bs);
    
    // here is a variable that contains the buffer content as a String
             content = new String(bs);
          } catch (IOException e) {
    
          } finally {
              is.close();
              dis.close();
          }
          System.out.println(content);
    }
    

    Edit(Answer to comment): Well, when we create the new String() we instantiate a new String with the byte[] value. But, as you already have an array of bytes, then you can store the value of the String object on it again using:

    bs = content.getBytes();
    

    In advance, don't worry if the print of the bytes are different, like [B@199c55a [B@faa824 It's just a name given to the object, but the value is the same on both.