Java Program to Convert contents of a file to byte array and Vice-Versa


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. Assume the file myData contains the following data −

Example

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

public class FileToByteArray {
   public static void main(String args[]) throws Exception{
      File file = new File("myData");
      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

Hi how are you welcome to Tutorialspoint


Updated on: 13-Mar-2020

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements