w3resource

Java: Read contents from a file into byte array


10. Read File into Byte Array

Write a Java program to read the contents of a file into a byte array.

Sample Solution:

Java Code:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
// Reading contents from a file into byte array.
public class Exercise10 { 
  public static void main(String a[]){       
        String file_name = "/home/students/test.txt";
        InputStream fins = null;
        try {
            fins = new FileInputStream(file_name);
            byte file_content[] = new byte[2*1024];
            int read_count = 0;
            while((read_count = fins.read(file_content)) > 0){
                System.out.println(new String(file_content, 0, read_count-1));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(fins != null) fins.close();
            } catch(Exception ex){
                 
            }
        }
    }
}

Sample Output:

Welcome to w3resource.com.                                                                                    
Append this text.Append this text.Append this text.                                                           
Append this text.                                                                                             
Append this text.                                                                                             
Append this text.                                                                                             
Append this text.

Flowchart:

Flowchart: Read contents from a file into byte array


For more Practice: Solve these Related Problems:

  • Write a Java program to read the entire contents of a file into a byte array using Java NIO.
  • Write a Java program to convert a file to a byte array and then reconstruct the file from the array.
  • Write a Java program to read a binary file into a byte array and display its hexadecimal representation.
  • Write a Java program to compare the byte arrays of two files to check if they are binary identical.

Go to:


PREV : Get File Size.
NEXT : Read File Line by Line.

JavaCode Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.