Java I/O stream methods for processing binary data include: FileInputStream and FileOutputStream: used to read and write binary files. DataInputStream and DataOutputStream: for advanced reading and writing of primitive data types and strings. Practical case example: reading and writing image files.
How Java I/O streams process binary data
Introduction
Java I/O Streams provide a mechanism for processing binary data and are crucial in file reading and writing, network communication, and data processing. This article will introduce the stream types used for processing binary data in Java, includingFileInputStream
,FileOutputStream
,DataInputStream
, andDataOutputStream
.
FileInputStream and FileOutputStream
These two streams are used to read and write binary files.
Code example:
// 从文件读取二进制数据 try (FileInputStream fis = new FileInputStream("data.bin")) { int data; while ((data = fis.read()) != -1) { System.out.println(data); } } // 向文件写入二进制数据 try (FileOutputStream fos = new FileOutputStream("data.bin")) { fos.write(1); fos.write(2); fos.write(3); }
DataInputStream and DataOutputStream
These two streams allow you to read in a more advanced way Write binary data, allowing you to read and write primitive data types and strings.
Code example:
// 从输入流中读取原始数据类型 try (DataInputStream dis = new DataInputStream(new FileInputStream("data.bin"))) { int i = dis.readInt(); double d = dis.readDouble(); } // 向输出流中写入原始数据类型 try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.bin"))) { dos.writeInt(42); dos.writeDouble(3.14); }
Practical case
You can use binary I/O streams to read and write images File:
// 读取图像文件 BufferedImage image = ImageIO.read(new File("image.jpg")); // 将图像写入二进制文件 try (FileOutputStream fos = new FileOutputStream("image.bin")) { ImageIO.write(image, "jpg", fos); }
Conclusion
Java I/O streams viaFileInputStream
,FileOutputStream
,DataInputStream
andDataOutputStream
provides a powerful mechanism for processing binary data. These streams allow you to read and write primitive data types, strings, and complex objects, which are useful in a variety of applications.
The above is the detailed content of How do Java I/O streams handle binary data?. For more information, please follow other related articles on the PHP Chinese website!