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

Problem printing the lines of a file Java

我正在学习如何读写 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)' 写的消息。 十分感谢。

您混合使用 2 种不同的方式来读取文件,结果是错误的。
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);