簡體   English   中英

獲取資源時出現 NullPointerException

[英]NullPointerException on getting Resource

以下代碼將在uri = ...上產生 NullPointerException

我試過ClassLoader.getSystemResourcegetClass().getResourcegetClass().getClassLoader().getResource

如果我在開頭刪除 / 或在結尾刪除它,請不要擔心,它仍然會產生 NullPointerException ..

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    private Main() {
        URI uri = null;

        try {
            uri = ClassLoader.getSystemResource("/resources/images/flags/").toURI();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        if (uri != null) {
            System.out.println(uri.toString());

            File folder = new File(uri);

            for (File file : folder.listFiles()) {
                System.out.println(file.getName());
            }
        }
    }
}

項目結構:

結構

請嘗試不使用“資源”,因為這只是文件夾的名稱。 此文件夾的內容將被復制到已編譯的類中。

這是我的評論的答案。 由於resource已經是類路徑的一部分,您必須更改:

"/resources/images/flags/" 

"/images/flags/"

此外,您可以嘗試相對路徑,如"images/flags/"

暫無
暫無

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

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