从jar加载资源



如何从构建的jar中获取资源文件夹中的文件对象?通过执行以下操作,我可以很容易地从IDE中完成这项工作,但这对jar文件不起作用。下面的代码只是在我的资源文件夹中创建一个文件的副本,并将其保存在用户机器上。

final ClassLoader classloader = Thread.currentThread().getContextClassLoader();
final InputStream configIs = classloader.getResourceAsStream("config.yml");

if(configIs != null) {
final File configFile = new File(chosenPath + "/config.yml");
Files.copy(configIs, configFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
configIs.close();
}

我一直在试图找出如何在罐子里做同样的事情,即使在阅读了许多其他文章后也没有取得多大成功。根据我的研究,提出了以下建议。下面的代码循环通过引用资源路径的所有路径。这会产生一个500KB以上的文本文件,所以我不确定哪一个是正确的,但即使我找到了正确的,我该怎么处理它?由于最后一个if语句检查名称以resourcePath开头,我认为这是正确的条目

Entry:config.yml path:resources/problems.json

但是,我该如何从它转换为输入流呢?如果有更好的方法,请告诉我,但到目前为止,我还没有找到关于这个主题的任何其他资源。

final String resourcePath = "resources/problems.json";
final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
if(jarFile.exists() && jarFile.isFile()) {  // Run with JAR file
System.out.println("Run as jar");
try {
final JarFile jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while(entries.hasMoreElements()) {
final String name = entries.nextElement().getName();
System.out.println("Entry:" + name + " path:" + resourcePath);
if (name.startsWith(resourcePath)) { //filter according to the path
System.out.println(name);
}
}
jar.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}

也许这会有所帮助:

/**
* Text files loaded with this method should work either within the IDE or your 
* distributive JAR file.<br><br>
* 
* <b>Example Usage:</b><pre>
* {@code 
*  try {
*       List<String> list = loadFileFromResources("/resources/textfiles/data_2.txt");
*       for (String str : list) {
*           System.out.println(str);
*       }
*   }
*   catch (IOException ex) {
*       System.err.println(ex);
*   } }</pre><br>
* 
* As shown in the example usage above the file path requires the Resource 
* folder to be named "resources" which also contains a sub-folder named 
* "textfiles". This resource folder is to be located directly within the 
* Project "src" folder, for example:<pre>
* 
*      ProjectDirectoryName
*          bin
*          build 
*          lib
*          dist
*          src
*              resources
*                  images
*                      myImage_1.png
*                      myImage_2.jpg
*                      myImage_3.gif
*                  textfiles
*                      data_1.txt
*                      data_2.txt
*                      data_3.txt
*          test</pre><br>
* 
* Upon creating the resources/images and resources/textfiles folders within 
* the src folder, your IDE should have created two packages within the Project 
* named resources.images and resources.textfiles. Images would of course be 
* related to the resources.images package and Text Files would be related to 
* the resources.textfiles package.<br>
* 
* @param filePath (String) Based on the example folder structure above this 
* would be (as an example):<pre>
* 
*    <b>  "/resources/textfiles/data_2.txt"  </b></pre>
* 
* @return ({@code List<String>}) A List of String containing the file's content.
*/
public List<String> loadFileFromResources(String filePath) throws java.io.IOException {
List<String> lines = new ArrayList<>();
try (java.io.InputStream in = getClass().getResourceAsStream(filePath);
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
reader.close();
}
return lines;
}

最新更新