我有一个 .txt 文件和一个名为 res 的文件中的图像。我也将文件添加到我的路径中。我编写了下面的代码,它在我的 Eclipse IDE 中工作得很好。导出 jar 并运行它时,它什么也不做。用cmd运行jar说找不到类路径。所以我尝试了第二 block 代码但没有成功。我的图像在那里效果很好。 bgi = new ImageIcon(getClass().getResource("bg.png"));
Scanner s = null;
try {
s = new Scanner(new File("res//10kaddress.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayList<String> paddress = new ArrayList<String>();
while (s.hasNext()){
paddress.add(s.next());
}
s.close();
所以我尝试在下面执行此操作,无论我做什么它都不会读取txt文件
URL url = GUI.class.getResource("10kaddress.txt");
File ff = new File(url.getPath());
Scanner s = null;
try {
s = new Scanner(ff);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayList<String> paddress = new ArrayList<String>();
while (s.hasNext()){
paddress.add(s.next());
}
s.close();
并收到此错误
java.io.FileNotFoundException: C:\Users\Major%20Lee\Sketch\GUI\res\10kaddress.txt (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at GUI.main(GUI.java:68)
Exception in thread "main" java.lang.NullPointerException
at GUI.main(GUI.java:73)
任何帮助都会很棒。谢谢!
最佳答案
我会将其作为 ResourceStream 打开(或者我只使用 ResourceBundle),就像这样 -
InputStream is = getClass().getResourceAsStream("10kaddress.txt");
Scanner s = new Scanner(is);
关于java - 添加 .txt 文件作为资源 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20309354/