我的代码使用getClass()。getResource()来获取文件位置,但是当我创建jar文件时,即使我复制到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)
它有“!”在jar文件名之后。
URL pty = getClass().getResource("party.txt");
File file = new File(pty.getPath());
reader = new BufferedReader(new FileReader(file));
Scanner sc = new Scanner(reader);
这就是我使用的。有没有更好的方法来做到这一点?
res.sendFile('../public/index.js', {root: __dirname});
答案 0 :(得分:1)
使用
Scanner sc = new Scanner(ClassLoader.getSystemResourceAsStream("party.txt"));
然后在导出到jar
后你不会得到FileNotFoundException
答案 1 :(得分:-1)
尝试以下方法:
File file = new File(getClass().getClassLoader().getResource("relative/path/to/file/from/resources/dir").getPath());
reader = new BufferedReader(new FileReader(file));
我将假设您已将文件正确放置在资源目录中。