我能够成功地读取和写入 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();
}
}
}