簡體   English   中英

為什么我的 java.util.Scanner 不讀取我的文件?

[英]Why does my java.util.Scanner not read my File?

我的掃描儀不讀取由 BufferedReader 讀取的現有文件,但 BufferedReaders 不支持我的文件需要的 UTF-8 編碼。

我已經使用了 BufferedReader(即使使用 UTF-8,它沒有給我像“ä”(德語字母)這樣的字母,而是給了我尷尬的問號符號)。 我當然已經使用過掃描儀。

public ArrayList<String> getThemefile2() {
    Scanner s;
    try {
        s = new Scanner(themefile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return new ArrayList<>();
    }
    ArrayList<String> list = new ArrayList<>();
    while (s.hasNextLine()) {
        list.add(s.nextLine());
    }
    s.close();
    return list;
}

它只返回一個空的 ArrayList,但不會觸發 FileNotFoundException。 主題文件是一個現有的文件。

您需要為文件指定編碼,如果它不是您的系統默認值。 在您的情況下,這將是您創建Scanner

s = new Scanner(themefile, "UTF-8");

沒有要查看的文件,我們都只是在猜測問題所在。

這是一個猜測:沒有下一行,因此 while 循環立即中斷,您得到一個空的數組列表。 如果文本文件中根本沒有換行符,就會出現這種情況。

如果您使用的是 Java 8+,我建議您使用Files#lines方法:

try (Stream<String> stream = Files.lines(themeFile.toPath())) {
    stream.collect(Collectors.toList()); //need to be stored in a variable.
} catch (IOException e) {
    e.printStackTrace();
}

文件:

我在 api 28 級別上遇到了同樣的問題。 這對我有用:

s = new Scanner(new FileReader(themefile));

並且必須導入:

import java.io.FileReader;

暫無
暫無

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

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