Java file to byte array


 

Java file to byte array

In this section, you will learn how to reads the entire content of a file into a byte array.

In this section, you will learn how to reads the entire content of a file into a byte array.

Java file to byte array

In this section, you will learn how to reads the entire content of a file into a byte array. 

Description of code:

We have created an instance of InputStream class that takes the file. The byte array hold the data of the file and  the read() method of InputStream class read the whole file data into an array of bytes.

read() method- This method of InputStream class reads up to the length of bytes from the input stream into an array of bytes.

Here is the code:

import java.io.*;

public class FileToByteArray {
  public static void main(String[] argsthrows Exception {
    File file = new File("C:/new.txt");
    InputStream is = new FileInputStream(file);
    long length = file.length();
    byte[] bytes = new byte[(intlength];
    int offset = 0, n = 0;
    while (offset < bytes.length
        && (n = is.read(bytes, offset, bytes.length - offset)) >= 0) {
      offset += n;
    }
    is.close();
    String s = new String(bytes);
    System.out.println(s);
  }
}

Above code will file into a byte array.

Then the bye array is converted to String using following code:
String s = new String(bytes);
System.out.println(s);

and printed on the System console.

Ads