我能够成功地读取和写入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();
}
}
}
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();
}
}
}
答案 0 :(得分:7)
而不是阅读器中的while(true)
,请使用while( scan.hasNextLine() )