簡體   English   中英

Java:程序無法從其中讀取時列出txt文件的內容

[英]Java: Program not able to list contents of txt file when reading from it

我正在使用JavaFx在列表中顯示圖標的程序上工作。 我制作了一個靜態類,用於從txt文檔中查找特定ID。 最初,靜態塊會在每行中添加定義的項的ID和名稱,但是由於出現了這些問題,因此我嘗試查找問題的根源。

相反,我只是瀏覽了靜態塊中文本文件的內容,並將其打印到控制台。

這是我的代碼供參考:

public class ItemIds {
    public static int UNDEFINED_ID = -1;
    private static HashMap<String, Integer> items;
    static {
        items = new HashMap<String, Integer>();
        System.out.println(new File("res/ids/item ids.txt").exists());
        try {
            //should print out every line in the text file
            Files.lines(Paths.get("res/ids/item ids.txt")).forEach(s -> {
                System.out.println(s);
            });
        } catch (IOException e) {
            System.out.println("Unable to read specified file.");
            e.printStackTrace();
        }
    }

    public static int getId(final String name) {
        final Integer id = items.get(name);
        return id != null ? id : UNDEFINED_ID;
    }
}

但是,初始化此靜態類並調用靜態塊時得到的結果很奇怪。 它列出每一行都沒有錯誤,直到到達10691行,然后在該行引發“ JavaFX應用程序線程中的異常” java.lang.ExceptionInInitializerError。

但是,這使我特別奇怪的是,當我使用較小的文本文檔(條目較少)時,一切似乎都可以正常工作。 由於該文件包含將近14000行,因此我必須刪除〜4000行才能使用。

關於為什么要這樣做的任何想法? 任何反饋表示贊賞-謝謝

我無法重現此錯誤。 我已經創建了一個包含18K行的文件,並且您的程序運行正常。 因此,絕對要考慮檢查您的文件以及堆棧跟蹤。

現在回到異常ExceptionInInitializerError ,可能是以下情況:

ExceptionInInitializerError表示靜態初始化程序中發生了意外的異常。 拋出ExceptionInInitializerError表示在評估靜態初始化程序或靜態變量的初始化程序期間發生了異常。

class ItemIds
{
  static
  {
     // if something does wrong -> ExceptionInInitializerError
  }
}

由於靜態變量是在靜態塊中初始化的,因此也有可能引入錯誤。 一個例子:

class ItemIds
{
  static int v = D.foo();
}

=>

class ItemIds
{
  static int v;

  static
  {
    v = D.foo();
  }
}

因此,如果foo()變得瘋狂,則可以獲取ExceptionInInitializerError。

您是否以靜態塊形式展示了完整的代碼?

暫無
暫無

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

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