1、用字节流读写二进制文件 要求:用DataOutputStream+FileOutputStream类将1,2,...,100,这100个数字写入到文件d:\out1.bin里,然后再用DataInputStream+FileInputStream类将d:\out1.bin的内读出来,并输出到屏幕上。用DataOutputStream+FileOutputStream写入二进制数据时,直接调用DataOutputStream的writeInt()方法将一个int型数据写入到文件中。读入数据时用DataI
时间: 2024-03-06 09:47:49 浏览: 36
nputStream的readInt()方法读取int型数据即可。以下是示例代码:
```java
import java.io.*;
public class BinaryFileIO {
public static void main(String[] args) {
String filename = "d:\\out1.bin";
try {
// 写入二进制文件
DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename));
for (int i = 1; i <= 100; i++) {
dos.writeInt(i);
}
dos.close();
// 读取二进制文件
DataInputStream dis = new DataInputStream(new FileInputStream(filename));
while (dis.available() > 0) {
int data = dis.readInt();
System.out.print(data + " ");
}
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意,要用try-catch语句捕获可能抛出的IOException异常。在写入数据时,要先创建一个DataOutputStream对象,再用它的writeInt()方法写入数据。在读取数据时,要先创建一个DataInputStream对象,然后调用其available()方法判断文件是否还有未读数据,如果有,再用其readInt()方法读取数据并输出到屏幕上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)