Java应用程序无法在jar中找到资源文本文件

时间:2015-01-04 22:26:00

标签: java eclipse embedded-resource executable-jar

从可执行jar获取以下错误。在eclipse中运行良好,文件存在于jar中。

java.nio.file.FileSystemNotFoundException
    at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
    at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
    at java.nio.file.Paths.get(Unknown Source)
    at come.awana.app.utility.Utilities.createRecords(Utilities.java:37)
    at com.awana.app.gui.RecordDisplayPanel.<init>(RecordDisplayPanel.java:82)
    at com.awana.app.gui.GUIDriver.<init>(GUIDriver.java:36)
    at com.awana.app.gui.GUIDriver.InitalizeAndShowGUI(GUIDriver.java:65)
    at com.awana.app.gui.GUIDriver.access$0(GUIDriver.java:62)
    at com.awana.app.gui.GUIDriver$1.run(GUIDriver.java:54)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$400(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

获取文件如下:

URI resource = Utilities.class.getClassLoader().getResource("resources/names.txt").toURI();
names = createNameList(Paths.get(resource));

尝试阅读文件:

private static List<String> createNameList(Path path){

    List<String> temp = new ArrayList<>();

    try(BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset())){
        String line = null;
        while((line = reader.readLine()) != null){
            temp.add(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    /* do stuff with temp */
}

我假设它与资源尝试加载的方式有关,但不确定如何纠正。任何建议......

修改

虽然我会将更正后的代码发布给后来遇到这个问题的其他人(因为我讨厌当人们提出修复它时,然后不知道他们是如何解决问题的......谢谢MadProgrammer!

获取资源文件如下:

InputStream resource  Utilities.class.getClassLoader().getResourceAsStream("resources/names.txt");
names = createNameList(resource);

阅读文件:

private static List<String> createNameList(InputStream resource){

    List<String> temp = new ArrayList<>();

    try(BufferedReader reader = new BufferedReader(new InputStreamReader(resource))){
        String line = null;
        while((line = reader.readLine()) != null){
            temp.add(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    /* do stuff with temp */
}

0 个答案:

没有答案