【问题标题】:Files not found after packing everything up to a Jar-File, though its working in Eclipse将所有内容打包到 Jar-File 后找不到文件,尽管它在 Eclipse 中工作
【发布时间】:2022-01-25 00:54:42
【问题描述】:

所以我的程序终于在它的第一个版本中完成了。我可以在 Eclipse IDE 中毫无问题地运行它,但是一旦我将它打包到 Jar-File 中,它就找不到项目内文件夹中的文件(声明为源文件夹)。我已经知道,在编译时,文件夹结构发生了变化,我尝试解决这个问题,但它不起作用,我不想坚持这样的解决方法。
项目结构:

- src/main/java/
    + [my packages]
- resources/
     + configs/[some files]
     + languages/[some language files]
     + levelcards/[some images]

在我的程序中,我正在访问“configs”中的文件

new File("./resources/configs/[...]");

它工作得很好,因为该文件夹存在于项目中。编译后没有,所以我尝试了

new File("./configs/[...]");

但它也不起作用。
我期望无论我是在 Eclipse 中还是直接通过 JRE 启动它,它都能正常工作,尽管我不知道如何让它达到这一点。如果您能以任何方式帮助我,我将不胜感激!
格雷戈尔

【问题讨论】:

  • Jar 中的对象不是文件,您不能使用基于文件的 API 来访问它们。看Class.getResource / getResourceAsStream
  • 参见例如this
  • @greg-449 使用此方法时我不明白的是该方法所假设的文件结构...如果我说“Class.getResource("Test.properties")”,Test 在哪里.properties 必须被定位?
  • 查看我链接的问题中的答案
  • @greg-449 我没看到这个,对不起!

标签: java eclipse compilation project-structure


【解决方案1】:

例如:

假设有一个 Utility 类,它将从文件中读取并以字符串形式返回

class Utils{

public static String readFromFile(String filePath){
  InputStream inputStream=Utils.class.getResourceAsStream(filePath); //eg:- configs/temp_file.txt
/* Now once you get the InputStream there 
are lot of utility library to return as string */

String newLine = System.getProperty("line.separator");
 BufferedReader reader = new BufferedReader(
         new InputStreamReader(inputStream));
 StringBuilder result = new StringBuilder();
 for (String line; (line = reader.readLine()) != null; ) {
     if (result.length() > 0) {
         result.append(newLine);
     }
     result.append(line);
 }
 return result.toString();
}
}

【讨论】:

  • 是的!我了解您的解决方案,但我没有阅读某些行,但我正在使用“属性”类。根据具体情况,我还使用“属性”类来写入这些文件。有什么办法可以让您的解决方案适应这个问题?编辑:我已经更改了我的项目结构以使其与“Class.getResource()”一起使用,但现在我得到了一个 FileNotFound-Error,所以这个案例仍然是开放的。我在pastebin上上传了课程,你可以看看:pastebin.com/aGFPhjnB
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
  • 2012-12-03
相关资源
最近更新 更多