【问题标题】:.jar file FileNotFoundException when use getClass().getResource() [duplicate].jar 文件 FileNotFoundException 使用 getClass().getResource() [重复]
【发布时间】:2018-10-19 21:01:30
【问题描述】:

我的代码使用 getClass().getResource() 来获取文件位置,但是当我创建 jar 文件时,即使我复制到 jar 文件目录,它也找不到我的文件。

日志给了我一个奇怪的路径Server2018.jar!\com\company\party.txt 它有“!”在 jar 文件名之后。

java.io.FileNotFoundException: file:\C:\Users\baram\IdeaProjects\Server2018\out\artifacts\Server2018_jar\Server2018.jar!\com\company\party.txt (The filename, directory name, or volume label syntax is incorrect)
        at java.base/java.io.FileInputStream.open0(Native Method)
        at java.base/java.io.FileInputStream.open(Unknown Source)
        at java.base/java.io.FileInputStream.<init>(Unknown Source)
        at java.base/java.io.FileReader.<init>(Unknown Source)
        at com.company.FileManager.getVote(FileManager.java:285)
        at com.company.PieParty.createScene(PieParty.java:74)
        at com.company.PieParty.initFx(PieParty.java:58)
        at com.company.PieParty.access$100(PieParty.java:21)
        at com.company.PieParty$1.run(PieParty.java:48)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(Unknown Source)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(Unknown Source)
        at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
        at java.base/java.lang.Thread.run(Unknown Source)

这是我使用的。有没有更好的方法来做到这一点?

URL pty = getClass().getResource("party.txt");
File file = new File(pty.getPath());
reader = new BufferedReader(new FileReader(file));
Scanner sc = new Scanner(reader);

【问题讨论】:

  • 你可以简称为getResourceAsStream。
  • URL.getPath() 将 URL 转换为文件名。它只返回 URL 的路径部分,不保证是有效的文件名。正如其他人指出的那样,您不需要 File 只是为了从资源中获取 InputStream。

标签: java filereader relative-path java-io


【解决方案1】:

尝试以下方法:

File file = new File(getClass().getClassLoader().getResource("relative/path/to/file/from/resources/dir").getPath());
reader = new BufferedReader(new FileReader(file));

我假设您已将文件正确放置在资源目录中。

【讨论】:

  • 问题代码失败,因为“资源”不是文件系统上的文件。您的答案因同样的原因而失败。
【解决方案2】:

使用

Scanner sc = new Scanner(ClassLoader.getSystemResourceAsStream("party.txt"));

那么导出到jar后就不会得到FileNotFoundException

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 2012-12-14
    • 2019-05-13
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多