打印Java文件的行时出现问题



我正在学习如何用Java读写文件。举了很多例子,但在这个具体的例子中,我遇到了一个问题,只是不知道为什么,因为就我而言,与其他例子相比,没有什么变化。也许这只是一个我看不见的愚蠢错误。显然,名为"nair.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");
}
}

为了完整起见,这里有一个仅使用BufferedReader的等效解决方案。如其他答案中所述,您不需要同时使用ScannerBufferedReader

try {
BufferedReader br = new BufferedReader(new FileReader("naval.txt"));
String line;
while (((line = br.readLine()) != null)) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Not possible to read the file");
e.printStackTrace();
}

如果您使用的是java-8,则可以使用一行实现相同的功能:

Files.lines(Paths.get("naval.txt")).forEach(System.out::println);

最新更新