java_io_EOFException

问题分析

当输入过程中意外到达文件或流的末尾时,抛出此异常。此异常主要被数据输入流用来表明到达流的末尾。

解决方案

因为不知道流的末尾,当到达末尾的时候,抛出了此异常。这种异常主要被数据输入流用来表明到达流的末尾,建议捕获异常并退出读取输入流。

例如:

  java.io.EOFException
    at libcore.io.Streams.readAsciiLine(Streams.java:203)
    at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:579)
    at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:827)
    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)

代码示例

  public static void main(String[] args) {
      DataInputStream input = null;
      try {
        //do something
        // Read all characters, until an EOFException is thrown.
        input = new DataInputStream(new FileInputStream(FILENAME));
        while(true) {
          char num;
          try {
            num = input.readChar();
            System.out.println("Reading from file: " + num);
          }
          catch (EOFException ex1) {
            break; //EOF reached.
          }
          catch (IOException ex2) {
            System.err.println("An IOException was caught: " + ex2.getMessage());
            ex2.printStackTrace();
          }
        }
      }
      catch (IOException ex) {
        System.err.println("An IOException was caught: " + ex.getMessage());
        ex.printStackTrace();
      }
      finally {
        try {
          // Close the input stream.
          input.close();
        }
        catch(IOException ex) {
          System.err.println("An IOException was caught: " + ex.getMessage());
          ex.printStackTrace();
        }
      }
    }

参考文献