Byte Streams in Java are used to perform input and output of raw binary data. They handle data in the form of bytes (8-bit) and are mainly used for files, images, audio, video, and other non-text data.
InputStream and OutputStreamJava provides several subclasses of byte streams such as FileInputStream and FileOutputStream to read and write data from files.
// Writing bytes to a file using FileOutputStream
import java.io.FileOutputStream;
public class WriteByteExample {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("data.bin");
fos.write(65);
fos.write(66);
fos.write(67);
fos.close();
}
}
// Reading bytes from a file using FileInputStream
import java.io.FileInputStream;
public class ReadByteExample {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("data.bin");
int value;
while ((value = fis.read()) != -1) {
System.out.println(value);
}
fis.close();
}
}
In the writing example, numeric byte values are stored in a file. In the reading example, bytes are read one by one until the end of the file is reached (-1).
Type below to visualize how characters are converted into an 8-bit Byte Stream (ASCII values).
This mimics how OutputStream.write() sees your data.
BufferedInputStream