How to write contents of a file to byte array in Java?


The FileInputStream class contains a method read(), this method accepts a byte array as a parameter and it reads the data of the file input stream to given byte array.

Example

import java.io.File;
import java.io.FileInputStream;

public class FileToByteArray {
   public static void main(String args[]) throws Exception {
      File file = new File("HelloWorld");
      FileInputStream fis = new FileInputStream(file);
      byte[] bytesArray = new byte[(int)file.length()];
      fis.read(bytesArray);
      String s = new String(bytesArray);
      System.out.println(s);
   }
}

Output

//Class declaration
public class SampleProgram {
   /* This is my first java program.
      This will print 'Hello World' as the output
   */

   //Main method
   public static void main(String []args) {
      //prints Hello World
      System.out.println("Hello World");
   }
}

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 19-Dec-2019

668 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements