全部产品
云市场

java_io_EOFException

更新时间:2018-04-19 17:27:07

问题分析:

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

解决方案:

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

示例:

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

代码示例:

  1. public static void main(String[] args) {
  2. DataInputStream input = null;
  3. try {
  4. //do something
  5. // Read all characters, until an EOFException is thrown.
  6. input = new DataInputStream(new FileInputStream(FILENAME));
  7. while(true) {
  8. char num;
  9. try {
  10. num = input.readChar();
  11. System.out.println("Reading from file: " + num);
  12. }
  13. catch (EOFException ex1) {
  14. break; //EOF reached.
  15. }
  16. catch (IOException ex2) {
  17. System.err.println("An IOException was caught: " + ex2.getMessage());
  18. ex2.printStackTrace();
  19. }
  20. }
  21. }
  22. catch (IOException ex) {
  23. System.err.println("An IOException was caught: " + ex.getMessage());
  24. ex.printStackTrace();
  25. }
  26. finally {
  27. try {
  28. // Close the input stream.
  29. input.close();
  30. }
  31. catch(IOException ex) {
  32. System.err.println("An IOException was caught: " + ex.getMessage());
  33. ex.printStackTrace();
  34. }
  35. }
  36. }

参考文献:

  1. https://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html

  2. https://examples.javacodegeeks.com/java-basics/exceptions/java-io-eofexception-how-to-solve-eofexception/