Java在/ res文件夹中查找文件并使用Scanner

Eva*_*udd 0 java file filenotfoundexception

我的文件位于我的/ res中,更具体地说是在/ res/Menus/CharSelect中.我已经进入构建路径并确保res文件夹是类路径.但是,我的新扫描程序(文件)导致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();
    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*ieu 5

不要那样做.当您将创建一个罐子,你将无法访问该文件作为一个File对象,但作为一个URL从你必须得到InputStreamopenStream().

相反,使用Scanner(InputStream)with:

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)
Run Code Online (Sandbox Code Playgroud)