java - 添加 .txt 文件作为资源 Java

标签 java file url embedded-resource getresource

我有一个 .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/

相关文章:

java - RestyGWT 和 GWT 集成 : Cannot GET Resource

python - 改变读取文件的方向?

ios - iOS 中安装了 URL Scheme

c# - 在 URL 或 cookie 中安全传输对象的注意事项

java - 如何从 JavaFx 中的任务发送 int?

java - 如何将动态值传递到 FilenameFilter 中?

java - Files.createFile() 可以有异步行为吗?

php - 如何在 URL 中转义中文 Unicode 字符?

java - JUnit:如何在测试工具类中避免 "no runnable methods"

c# - 在 C# 中创建对象和对象序列化