这就是我写出文件的方式。
BufferedReader read = new BufferedReader(new FileReader(filetoreadfrom));
FileOutputStream fileStream = new FileOutputStream(filetowriteto);
DataOutputStream dataStream = new DataOutputStream(fileStream);
String temp;
while((temp = read.readLine()) != null){
String[]arrayTemp = temp.split("\\|");
dataStream.writeInt(Integer.parseInt(arrayTemp[0]));
dataStream.writeInt(Integer.parseInt(arrayTemp[1]));
dataStream.writeUTF(arrayTemp[2]); }
所以我试着写出一个二进制文件,它似乎工作正常。但是当我尝试将其读回来时,我最终获得了IOExceptions。
这是我在文件中阅读的内容。
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("data.bin")));
int one,two,eight;
String three,
while(true){
one = in.readInt();
two = in.readInt();
three = in.readUTF();}
我一直在查看
的数据流教程页面http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
根据我在示例中的理解,它显示通过捕获EOFException来捕获文件条件的结束?从我从api中可以看到,这是IOException的子类,这有助于我理解为什么我会得到它。
我不明白的是如何处理它而不会发生异常。我已经尝试过像in.read()== -1然后中断,但无济于事我仍然会抛出异常。
答案 0 :(得分:0)
API已经设计好了。你不能改变它的工作方式。与IOException分开捕获EOFException,关闭流并中断。捕获IOException时,记录错误,关闭流并中断。