我根据在网上找到的一些数据流示例编写了这个类,并且在每次运行结束时都会收到 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);
}
}
}
有没有人有任何建议或意见可以帮助清理这个问题,这样我就不会在文件中出现乱码,因此它不会捕获异常?我应该如何结束操作并关闭流?
最佳答案
对于输入操作,您将永远读取while(true)
,因此完成循环的唯一方法是抛出EOFException
。如果您不希望操作以这种方式完成,则必须在开始之前知道您正在读取多少个整数(并使用它来限制循环)。
文件看起来像乱码的原因是因为您将值写入为二进制。如果您想读取文件中的整数,则必须将它们写为文本。
此外,您应该在每个 case 的末尾放置 break;
语句。
关于java - 数据流捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14451455/