簡體   English   中英

Java在/ res文件夾中查找文件並與它一起使用掃描儀

[英]Java Finding a file in /res folder and using Scanner with it

我的文件位於我的/ res中,更具體地說,位於/ res / Menus / CharSelect中。 我已經進入構建路徑,並確保res文件夾是類路徑。 但是,我的新Scanner(file)導致NullPointerException。 當我做file.exists(); 它返回FALSE ...,我不知道為什么。 我100%確實存在該文件,並且該文件位於CharSelect文件夾中。 有人可以幫忙嗎? 提前致謝。

    file = new File(getClass().getResource("/Menus/CharSelect/Unlocked.txt").getPath());
    try
    {
        scanner = new Scanner(file);
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }

不要那樣做 創建jar時,您將不能以File對象的形式訪問該文件,而只能以URL形式訪問該URL ,而必須使用openStream()獲得InputStream

而是將Scanner(InputStream)與以下項一起使用:

try (InputStream is = getClass().getResource("/Menus/CharSelect/Unlocked.txt").openStream()) {
    scanner = new Scanner(is);
    ...
} // is.close() called automatically by try-with-resource block (since Java 7)

someClass.getResource解析相對於someClass位置的路徑。 將文件移到PATH_TO_THIS_CLASS_PATH / Menus / CharSelect / Unlocked.txt,操作必須成功

暫無
暫無

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

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