In Java, there are dozens of ways to read a binary file. The following shows one method of reading the header from a bitmap file to see if it really is a bitmap file!
A missing or moved file is not an exceptional event, first we check our file actually exists:
File myfile = new File("myfile.bmp");
if (myfile.isFile()){
// If we are here, then our file exists!
}else{
System.out.println("The file does not exist or is not a file!");
}
The reason we use 'isFile()' instead of 'exists()' is that if myfile was given a directory / folder that exists, it would pass the check. We are only interested in actual files.
The following uses a 'try with resources' block to handle opening our file. This try block also takes care of closing our file and catches any exceptions that could occur. In this instance, an exceptional event could be the file going offline mid read. With a binary file, another common exception event is trying to read more bytes then there actually are...
After opening our file, we create a 14 byte array (the size of the bitmap header) and use the read method to fill that array with the first 14 bytes of the file. Click the following to find out more about Java arrays.
try(FileInputStream infile = new FileInputStream(myfile)){
byte[] header=new byte[14];
infile.read(header);
// Check the header to see if the file is a bitmap image
}catch(IOException e){
System.out.println("There was a problem opening this file!");
System.out.println(e);
}
Once we have read the first 14 bytes into our array, we check that the first two bytes are 'BM', if not then the file is not a standard BM file!
if (header[0]!='B' && header[1]!='M'){
System.out.println("This does not look like a bitmap file...");
}else{
System.out.println("This file is probably a bitmap file");
}
With the Java JDK installed, from a command line:
If you do not have Java JDK installed, click the following link to find out how to install Java on your computer!
import java.io.*;
class Readbinary{
public static void main(String[] arguments){
File myfile = new File("myfile.bmp");
if (myfile.isFile()){
try(var infile = new FileInputStream(myfile)){
byte[] header=new byte[14];
infile.read(header);
if (header[0]!='B' && header[1]!='M'){
System.out.println("This does not look like a bitmap file...");
}else{
System.out.println("This file is probably a bitmap file!");
}
}catch(IOException e){
System.out.println("There was a problem opening this file!");
System.out.println(e);
}
}else{
System.out.println("The file does not exist?");
}
}
}
Updated (28/06/2026)