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

时间:2014-09-03 14:56:58

标签: java file-io java-8

它旁边有一个可运行的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文件,但更易读?

2 个答案:

答案 0 :(得分:2)

有两种方法可以找到类文件的基本路径,您可能会发现它们都比必要的更复杂。

首先是您在问题中已经提到的内容:

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"));

答案 1 :(得分:0)

你有没有set the Class-Path of the Jar file?如果你包含一个"。"在课程路径中,我认为它会像你最初想象的那样工作。

在Jar文件的清单中:

  

Class-Path:。

在代码中:

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

我还没有对此进行过测试,但我已经完成了类似的工作,我相信它会起作用。

相关问题