繁体   English   中英

简化在与 .jar 相同的文件夹中打开文件

[英]Simplify opening the file in the same folder as .jar

旁边有一个可运行的 jar 文件和data.txt文件。 data.txt可能会动态更改。 程序需要读取这个文件的内容。 我第一次尝试打开文件不起作用:

new InputStreamReader(getClass().getResourceAsStream("/data.txt"), "UTF-8");

我得出了以下解决方案,但它很复杂,而且有点尴尬:

new InputStreamReader(new FileInputStream(new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath()).getParent() + "/data.txt"), "UTF-8");

很难理解这里发生了什么。

我尝试了new File("./data.txt")并且抛出了 NPE。

如何打开与 .jar 文件位于同一文件夹中但更易读的data.txt文件?

有两种方法可以定位类文件的基本路径,您可能会发现这两种方法都比必要的复杂。

第一个是你已经在你的问题中:

URL url = MyClass.class.getProtectionDomain().getCodeSource().getLocation();

第二个是

URL url=MyClass.class.getResource("MyClass.class");
if(url.getProtocol().equals("jar"))
    url=((JarURLConnection)url.openConnection()).getJarFileURL();
else url=MyClass.class.getResource("/");// for file: directories

URL您可以获得一个UTF-8 Reader

Reader r = Files.newBufferedReader(Paths.get(url.toURI()).resolveSibling("data.txt"));

您是否设置了 Jar 文件的Class-Path 如果包含“.” 在课程路径中,我认为它会像您最初设想的那样工作。

在 Jar 文件的清单中:

类路径:。

在代码中:

InputStream ins = getClass().getResourceAsStream("/data.txt");
... // do stuff with stream

我没有测试过这个,但我做过类似的事情,我相信它会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM