How to Convert File to Byte[] in Java


In this example, we will learn how to convert file to byte[] in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class File2ByteExample {

    public static void main(String[] args) {

    	byte[] bFile = null;
    	int n = 0;
        try 
        {  
            File file = new File("example.txt");  
            FileInputStream fi = new FileInputStream(file);  
            ByteArrayOutputStream bo = new ByteArrayOutputStream(1000);  
            byte[] b = new byte[1000];  
              
            while ((n = fi.read(b)) != -1) 
            {  
                bo.write(b, 0, n);  
            }  
            fi.close();
            bo.close();  
            bFile = bo.toByteArray();
            for (int i = 0; i < bFile.length; i++)
            {
                System.out.print((char) bFile[i]);
            }
        } 
        catch (FileNotFoundException e) 
        {  
            e.printStackTrace();  
        }
        catch (IOException e) 
        {  
            e.printStackTrace();  
        } 
    }
}

Output:

test
read
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments