我根据我在网上找到的一些关于数据流的示例编写了这个类,并且在每次运行结束时我都会收到一个 EOFException。当我查看它时,它说意外到达了溪流的尽头。它似乎在控制台上工作(至少它吐出正确的数字序列)。虽然当我在运行后检查内容时,文本文件只是乱码。
public class DataStreamExample {
public static void main(String args[]) {
int choice = 0;
int[] numbers = { 25, 4, 19, 70, 12, 28, 39, 30 };
System.out.println("This program will provide an example on how the Data Stream works.");
System.out.println("Note: Data Streams only work with primative data types.");
System.out.println();
System.out.println();
try {
System.out.println("1. For write Data operation");
System.out.println("2. For read Data operation");
System.out.println("Enter the number for the operation of your choice: ");
BufferedReader buffRead = new BufferedReader(new InputStreamReader(System.in));
choice = Integer.parseInt(buffRead.readLine());
switch(choice){
case 1:
FileOutputStream fileOut = new FileOutputStream("Example.txt");
BufferedOutputStream buffOut = new BufferedOutputStream(fileOut);
DataOutputStream dOutput =new DataOutputStream (buffOut);
for (int i = 0; i < numbers.length; i ++) {
dOutput.writeInt(numbers[i]);
}
System.out.print("writing data ");
dOutput.close();
case 2:
FileInputStream fileIn = new FileInputStream("Example.txt");
BufferedInputStream buffIn = new BufferedInputStream(fileIn);
DataInputStream dInput = new DataInputStream (buffIn);
while (true){
System.out.print(dInput.readInt());
}
default:
System.out.println("Invalid choice");
}
}
catch (Exception e) {
System.err.println("Error in read/write data to a file: " + e);
}
}
}
有没有人有任何建议或观察可以帮助清理这个问题,所以我不会在文件中出现乱码,所以它不会捕获异常?我应该如何结束操作并关闭流?