簡體   English   中英

無法讀取 integer 文件

[英]Can't read integer file

我正在嘗試從包含整數的文件中讀取數據,但掃描程序未從該文件中讀取任何內容。

我試圖從Scanner讀取文件:

// switch() blablabla 
case POPULATION:
            try {
                while (sc.hasNextInt()) {
                    this.listePops.add(sc.nextInt());
                }
            } catch (Exception e) {
                System.err.println("~ERREUR~ : " + e.getMessage());
            }
            break;

如果我嘗試將每個sc.nextInt()打印到控制台,它只會打印一個空行然后停止。 現在,當我讀取與String相同的文件時:

?652432
531345
335975
164308
141220
1094283
328278
270582
// (Rest of the data)

所以,我猜它不能將文件作為整數列表讀取,因為開頭有一個問號,但問題是這個問號沒有出現在我的文件中的任何地方,所以我無法刪除它。 我應該做些什么?

如果文件中的第一個字符是問號 ( ? ) 並且其原始來源未知,那么它通常是UTF-8字節順序標記(BOM)。 這意味着文件保存為 UTF-8。如果該文件保存為 UTF-8 而不是 ANSI,Microsoft 記事本應用程序將向保存的文本文件添加 BOM。 UTF-16、UTF-32 等還有其他 BOM 字符。

以 String 形式讀取文本文件現在看起來並不是一個壞主意。 更改文件的保存格式可以工作,但 BOM 可能具有其他應用程序的實際預期目的,因此,這可能不是一個可行的選擇。 讓我們將文件讀取為 String 行(讀取代碼中的注釋):

// Variable to hold the value of the UTF-8 BOM:
final String UTF8_BOM = "\uFEFF";

// List to hold the Integer numbers in file.
List<Integer> listePops = new ArrayList<>();
    
// 'Try With Resources' used to to auto-close file and free resources.
try (Scanner reader = new Scanner(new File("data.txt"))) {
    String line;
    int lineCount = 0;
    while (reader.hasNextLine()) {
        line = reader.nextLine();
        line = line.trim();
        // Skip blank lines (if any):
        if (line.isEmpty()) {
            continue; 
        }
        lineCount++;
        /* Is this the first line and is there a BOM at the 
           start of this line? If so, then remove it.    */
        if (lineCount == 1 && line.startsWith(UTF8_BOM)) {
            line = line.substring(1);
        }
            
        // Validate Line Data:
        // Is the line a String representation of an Integer Number?
        if (line.matches("\\d+")) {
            // Yes... then convert that line to Integer and add it to the List.
            listePops.add(Integer.parseInt(line));
        }
        // Move onto next file line...
    }
}
catch (FileNotFoundException ex) {
    // Do what you want with this exception (but don't ignore it):
    System.err.println(ex.getMessage());
}
    
// Display the gathered List contents:
for (Integer ints : listePops) {
    System.out.println(ints);
}

看起來Scanner無法將文件讀取為整數列表,因為文件開頭有一個問號。 這可能是由於多種原因造成的,例如文件開頭的隱藏字符,或者文件的編碼問題。

您可以嘗試的一件事是使用不同的工具來讀取文件,例如 BufferedReader 類。 此類允許您將文件逐行讀取為字符串,然后您可以使用Integer.parseInt()方法將字符串解析為整數。 這是您如何執行此操作的示例:

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
    int value = Integer.parseInt(line);
    this.listePops.add(value);
}

暫無
暫無

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

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