我能够成功地用 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/