如何将资源文件打包到可运行的jar中 [英] How can I package a resource file into a runnable jar
问题描述
我已经尝试过许多方法,并遵循了几个在线说明,例如 -
Eclipse导出Runnable JAR不显示图像
但到目前为止,没有成功。
I have tried this in many ways, and followed several online instructions, such as this - Eclipse exported Runnable JAR not showing images But so far, no success.
我有一个非常简单的程序它读取文本文件(test.txt)并将其内容打印到标准输出。我正在使用Eclipse。这是我所做的 -
I have a very simple program that reads a text file (test.txt) and prints out its contents to standard output. I am using Eclipse. Here is what I have done-
- 我将文本文件放入一个名为资源的文件夹
- 我右键单击资源文件夹,选择构建路径并点击用作资源文件夹
- 在我的代码中,我尝试了两种方法来解决文件 - (a)作为/test.txt和(b)作为resources / test.txt,当我在Eclipse中运行程序时,后一种方法有效,但是当我将项目导出为可运行的jar文件时,这两种方法都不工作,资源文件夹没有包含在jar文件中。
任何帮助将不胜感激。
附录:
这是代码。
Addendum: Here is the code.
public class FileIOTest {
public static void main(String[] args) {
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(new File("/test.txt")));
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
}
}
推荐答案
无法通过 FileReader
访问Jar文件中的资源,因为它不是文件系统上的文件。 Java确实有一种访问类路径(包括Jars)资源的机制: ClassLoader.getResourceAsStream()。您可以使用它与您的默认类加载器:
You can not access a resource in a Jar file through a FileReader
because it is not a file on the file system. Java does have a mechanism for accessing resources in your classpath (including in Jars): ClassLoader.getResourceAsStream(). You can use it with your default classloader:
BufferedReader br = new BufferedReader(new InputStreamReader(
ClassLoader.getSystemClassLoader()
.getResourceAsStream("resource/test.txt")));
请注意, getResourceAsStream
返回 null
而不是抛出异常,所以你可能想要先获取流,检查是否为 null
,然后抛出异常或处理它。
Note that getResourceAsStream
returns null
instead of throwing an exception, so you may want to get the stream first, check if for null
, then either throw an exception or process it.
您将希望将jar中的完整路径作为路径。
You will want to give the full path within the jar as your path.
这篇关于如何将资源文件打包到可运行的jar中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!