Being able to write bytes to a file is useful if you need to create a non-text file. As always with Java, there are many of doing this. The following is one of the simplest ways to create a file and write some bytes to it.
In general, it is unlikely you will write individual bytes to a file. The full example below writes the contents of a byte array to file. These are the two key lines:
// This is our byte array, so we can view the output, these are ASCII codes for the letters A B C byte letters[]={65,66,67}; // This writes the entire array to the file (stream) opened fo.write(letters);
To make it easier to demonstrate, the output file created by our full program can be opened in a text editor. The array of bytes could just have easily been a file header, pixels of a bitmap or any other kind of binary blob.
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 Writebytes{
public static void main(){
final String myfile="output2.txt";
// This following are ASCII codes for the letters A B C
byte letters[]={65,66,67};
try(var fo = new FileOutputStream(myfile)){
fo.write(letters);
System.out.println("File "+myfile+" saved!");
}catch(IOException e){
// Problem writing file...
System.out.println("There was a saving "+myfile);
System.out.println(e);
}
}
}
Updated (30/10/2026)
Java File Handling:
Read Text |
Write Text |
Read Binary |
Write Binary