Java 创建包含外部文件的 Runnable Jar
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18091046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating Runnable Jar with external files included
提问by Anup
I want to build a runnable jar in java. I need to include some of the files in the jar so that when I execute jar the files are automatically read from the java class. Hence I created a folder in the project and referred these files from the project. I created jar file following some tutorial but I could not able to include these external files in my jar file. Please let me about creating runnable jar with external files.
我想在java中构建一个可运行的jar。我需要在 jar 中包含一些文件,以便当我执行 jar 时,这些文件会自动从 java 类中读取。因此我在项目中创建了一个文件夹并从项目中引用了这些文件。我按照一些教程创建了 jar 文件,但我无法在我的 jar 文件中包含这些外部文件。请让我了解如何使用外部文件创建可运行的 jar。
My file struture is
我的文件结构是
Test
|
|
-------src
| |
| default package
| |
| |
| test1.java
|
-------FileFOlder
| |
| |
| abc.txt
I am accessing abc.txtin test1.javaclass. My code is,
我在test1.java类中访问abc.txt。我的代码是,
public class test1 {
public static void main(String[] args) throws IOException {
char [] read = new char[20];
String path = new File(".").getCanonicalPath();
path = path+"\Newfolder\abc.txt";
System.out.println(path);
File nF = new File(path);
FileReader fR = new FileReader(nF);
fR.read(read);
for(char c : read){
System.out.print(c);
}
fR.close();
System.out.println(" Hi..This is test program ");
}
}
When I create executable jar using eclipse export option, I am unable to see FileFolder directory inside the jar. Please give me some information regarding this.
当我使用 eclipse 导出选项创建可执行 jar 时,我看不到 jar 中的 FileFolder 目录。请给我一些关于这方面的信息。
采纳答案by Daniel Kaplan
Here's what you should do instead:
这是你应该做的:
Put that file back inyour jar file. Use class.getResourceAsStream()
to read it instead of File
and FileReader
. Here is an explanation of how to do that: How to really read text file from classpath in Java
把该文件回在你的jar文件。使用class.getResourceAsStream()
读它,而不是File
和FileReader
。这是如何做到这一点的解释:How to real read text file from classpath in Java
回答by scottysseus
Problem Solved!
问题解决了!
here is how:
方法如下:
1) right click your project folder and create a new folder.
1)右键单击您的项目文件夹并创建一个新文件夹。
2) move all of your files that you want packed into the jar into that folder.
2) 将所有要打包到 jar 中的文件移动到该文件夹中。
3) click project -> properties -> Build Path -> Source -> Add Folder
and select that folder you just created.
3) 单击project -> properties -> Build Path -> Source -> Add Folder
并选择您刚刚创建的文件夹。
4) create your JAR!
4)创建你的JAR!
Since you already have created your folder with abc.txt insideit, you can skip steps 1 and 2
由于您已经在里面创建了 abc.txt 的文件夹,因此您可以跳过步骤 1 和 2
EDIT: one way you can make sure your JAR contains these files is to use 7zip.
编辑:确保 JAR 包含这些文件的一种方法是使用 7zip。