我正在学习如何用 Java 读写文件。做了很多例子,但在这个特定的例子中我遇到了问题,只是不知道为什么,因为就我而言,与其他例子相比没有任何改变。也许只是一个我看不到的愚蠢错误。显然,名称为“naval.txt”的文件是在相应的源上创建并保存的。这是我的代码:
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("naval.txt"));
String line;
while (((line = br.readLine()) != null)) {
Scanner sc = new Scanner(line);
System.out.println(sc.next());
}
} catch (IOException e) {
e.getMessage();
System.out.println("Not possible to read the file");
}
}
它甚至没有读过它。如果我运行它,它会显示我为“catch(Exception e)”编写的消息。 万分感谢。
最佳答案
您混合了两种不同的方式来读取文件,结果是错误的。
Scanner 对象没有构造函数,以字符串作为参数。
只需使用 Scanner
打开文件并读取其行:
public static void main(String[] args) {
try {
Scanner sc = new Scanner(new File("naval.txt"));
String line;
while (sc.hasNext()) {
line = sc.nextLine();
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e.getMessage() + "\nNot possible to read the file");
}
}
关于java - 打印文件 Java 的行时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53688073/