java - 无法使用文件的 URL

标签 java file url resources

我的旧版本可以工作,但如果我尝试导出到可运行的 Jar 文件,它不会加载 txt 文件。

public String jarLocation = getClass().getProtectionDomain()
        .getCodeSource().getLocation().getPath();
public File txt = new File(jarLocation + "/images/gewinne.txt");

之后我尝试使用 get Resource,但文件无法加载 URL 部分:/我迷路了

public URL urlGewinne = Kalender.class.getResource("/images/gewinne.txt");
public File txt = new File(urlGewinne); // ERROR

public void txtLesen() throws IOException {
    try {
        BufferedReader br = new BufferedReader(new FileReader(txt));
        String line = null;
        while ((line = br.readLine()) != null) {
            gewinne.add(line);
        }

        br.close();
    } catch (FileNotFoundException ex) {

    }
}

最佳答案

原因很明显:资源不是文件。 从 jar 文件中获取的资源是该 jar 的一部分、jar 的条目等,但不是在文件系统中找到的单独文件。

好消息是您根本不需要文件。如果成功获取资源,您可以直接获取其流并从此流中读取:

换行

URL urlGewinne = Kalender.class.getResource("/images/gewinne.txt");

InputStream urlGewinne = Kalender.class.getResourceAsStream("/images/gewinne.txt");

这一行:

BufferedReader br = new BufferedReader(new FileReader(txt));

BufferedReader br = new BufferedReader(new InputStreamReader(txt));

其余代码应该可以工作。

关于java - 无法使用文件的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33551159/

相关文章:

java - JDBC 查询第二次运行速度更快

java - 关于java编程中的有理数,计算(1/2+3/4+...+99/100)^2

java - 位移乘法循环

c++ - 为什么要使用 C++ 头文件?

linux - 如何在 bash 脚本中对 url 进行编码?

java - 来自 Android 相机的图像,正面朝上

database - 什么是基于文件的数据库?

android - 如何通过 ACTION_VIDEO_CAPTURE 操作将文件输出设置为 mp4?

java - 我如何在 Java 中转义 URL(文档不清楚)?

url - 谷歌电子表格 : Show Document URL in cell. 可能吗?