w3resource

Java: Read contents from a file into byte array

Java Input-Output: Exercise-10 with Solution

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

JavaCode Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to get file size in bytes, kb, mb.
Next: Write a Java program to read a file content line by line.

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.