java - 从二进制文件读取返回 -1 而不抛出 EOFException

标签 java file eofexception

我正在尝试从文件中读取一字节整数。整数读取正确,但进程不断读取整数“-1”,而不会引发 EOF 异常。

这就是我将整数写入文件的方式。我从class1.dat中读取4个字节整数,并将低于256的那些作为1字节整数放入output1.dat中。

FileInputStream fis = new FileInputStream("D:\\class1.dat");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
FileOutputStream fos = new FileOutputStream("D:\\output1.dat");
DataOutputStream dos = new DataOutputStream(fos);

try
{
     while(true) 
     {
         number = dis.readInt();
         System.out.println("Integer read : " + number);

         if(number < 256)
             dos.write(number);

     }
}
catch(EOFException e)
{
      dis.close();
      dos.close();
}

这就是我从output1.dat读取1字节整数的方法。

DataInputStream dis = new DataInputStream(new FileInputStream("D:\\output1.dat"));


try
{
      int number;

      System.out.println("File with < 256");

      while(true)
      {
            number = dis.read();
            System.out.println("Number =  "  + number);
      }

}
catch(EOFException e)
{
      dis.close();
}

为什么不抛出 EOFException?

最佳答案

不会抛出 EOF 异常,因为您使用了 DataInputStream 的 read 方法,该方法实际上是从 FilterInputStream 继承的。

这里的文档:https://docs.oracle.com/javase/7/docs/api/java/io/FilterInputStream.html#read()

Returns: the next byte of data, or -1 if the end of the stream is reached.

到达流末尾时不会引发异常。

您可能需要使用 readByte 方法,当输入流到达末尾时,该方法会抛出 EOFException。

关于java - 从二进制文件读取返回 -1 而不抛出 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37571762/

相关文章:

java - PriorityQueue的顺序错误

c++ - fgets 中的 vector 类型

Hadoop + Hbase 兼容性问题

java - 运行程序并观察输出为: 55 4 50 19

java.lang.ClassNotFoundException : sun. jdbc.odbc.JdbcOdbcDriver 发生异常。为什么?

java - 如何在PHP服务器上显示android POST字符串?

c - 文件指针会随着文件位置的变化而移动吗?

Java:哪个具有更好的性能 - 将流推送到字符串?

java - 在java中读取对象直到文件结束

java - 无法通过 Java 中的 ObjectInputStream 发送对象