簡體   English   中英

打印文件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)'寫的消息。 非常感謝。

您混合使用兩種不同的方式讀取文件,結果是錯誤的。
沒有使用字符串作為參數的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM