gpt4 book ai didi

java - 无法使用文件的 URL

转载 作者:行者123 更新时间:2023-12-01 10:57:29 25 4
gpt4 key购买 nike

我的旧版本可以工作,但如果我尝试导出到可运行的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com