Java - 读取和写入文本文件

djm*_*gal 0 java

我成功地能够读取和写入Java中的示例文本文件.但是,当我尝试从文件中读取时,它总是在到达文件末尾时抛出NoSuchElementException.我已经修改了代码以通过打印"Reached end of file"来捕获此异常,但我想知道这是否正常; 我不喜欢它,我觉得我错过了什么.

任何帮助表示赞赏.这是我的代码:

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();
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

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();
     }
  }
Run Code Online (Sandbox Code Playgroud)

}

clc*_*cto 7

而不是while(true)在读者中使用while( scan.hasNextLine() )