Java - 读取和写入文本文件

标签 java

我能够成功地用 Java 读取和写入示例文本文件。但是,当我尝试从文件中读取时,它总是在到达文件末尾时抛出 NoSuchElementException 。我修改了代码以通过打印“到达文件末尾”来捕获此异常,但我想知道这是否正常;我不这么认为,我觉得我错过了一些东西。

感谢任何帮助。这是我的代码:

MyFileWriter.java

import java.io.*;

public class MyFileWriter {

   public static void main(String[] args) {
      File file = new File("MyFile.txt");
      PrintWriter out = null;

      try {
         out = new PrintWriter(file);
         out.write("This is a text file.");
      } catch(IOException e) {
         e.printStackTrace();
         System.out.println("IOException: " + e.getMessage());
      } finally {
         out.flush();
         out.close();
      }
   }
}

MyFileReader.java

import java.io.*;
import java.util.*;

public class MyFileReader {
  public static void main(String[] args) {

     File file = new File("MyFile.txt");
     Scanner scan = null;

     try {
        scan = new Scanner(file);
        while(true) {
           String next = scan.nextLine();
           if(next != null) {
              System.out.println(next);
           }
           else {
              break;
           }
        }
     } catch(IOException e) {
        e.printStackTrace();
        System.out.println("IOException: " + e.getMessage());
     } catch(NoSuchElementException e) {
        System.out.println("***Reached end of file***");
     } finally {
        scan.close();
     }
  }

}

最佳答案

在阅读器中使用 while( scan.hasNextLine() ) 代替 while(true)

关于Java - 读取和写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19455092/

相关文章:

java - 韩文未出现在Apache Netbeans中

java - 使用 Java 私有(private)方法(JDK 类)安全吗?

java - Java 中的 ISO-8859-1 到 UTF-8

java - 有人可以总结一下 Java 接口(interface)的可见性选择吗?

java - for-each 循环如何工作?

java - Ant taskdef - 需要类路径和 -lib 参数?

java - 在电脑上运行 vaadin 应用程序

java - 无法在自定义登录模块中注入(inject) dao

java - 导出为CSV编码问题

java - 使用jdbc连接oracle数据库