Java 如何在可执行 Jar 中包含文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2671796/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:37:55  来源:igfitidea点击:

How to include text files with Executable Jar

javajarexecutable

提问by Jake

Hi guys rookie Java question.

大家好,新手Java问题。

I have a Java project and I want to include a text file with the executable jar. Right now the text file is in the default package.

我有一个 Java 项目,我想在可执行 jar 中包含一个文本文件。现在文本文件在默认包中。

InputFlatFile currentFile = new InputFlatFile("src/theFile.txt");

InputFlatFile currentFile = new InputFlatFile("src/theFile.txt");

I grab the file with that line as you can see using src. However this doesn't work with the executable jar.

正如您使用 src 看到的那样,我使用该行抓取文件。但是,这不适用于可执行 jar。

Can someone please let me know how to keep this file with the executable jar so someone using the program can just click a single icon and run the program.

有人可以让我知道如何将此文件与可执行 jar 一起保存,以便使用该程序的人只需单击一个图标即可运行该程序。

Thanks!

谢谢!

采纳答案by Romain Hippeau

The base directory in the jar file is in the classpath.

jar 文件中的基本目录位于类路径中。

Try InputFlatFile currentFile = new InputFlatFile("theFile.txt");

试试 InputFlatFile currentFile = new InputFlatFile("theFile.txt");

You are probably using an IDE and it has a src folder in it that the IDE uses for the base of the packages. When you create the jar file from the IDE it then removes the src folder and the root folder has the packages in it.

您可能正在使用 IDE,并且其中有一个 src 文件夹,IDE 将其用作包的基础。当您从 IDE 创建 jar 文件时,它会删除 src 文件夹,根文件夹中包含包。

i.e. in eclipse src/com.blah.blah once jar file is created the structure becomes com.blah.blah

即在 eclipse src/com.blah.blah 中,一旦创建了 jar 文件,结构就变成了 com.blah.blah

Of course I assume that InputFlatFile is properly reading the value.

当然,我假设 InputFlatFile 正确读取值。

http://www.devdaily.com/blog/post/java/read-text-file-from-jar-file

http://www.devdaily.com/blog/post/java/read-text-file-from-jar-file

回答by Sanjay Manohar

you want it IN the executable jar? then to read the file you should use

你想要它在可执行 jar 中吗?然后读取您应该使用的文件

getClass().getResourceAsStream()

to read the file.

读取文件。

Keep the text file in the package you want to access it from. The classloader will find it.

将文本文件保存在要从中访问它的包中。类加载器会找到它。

Remember also that filenames in JARs are case sensitive.

还要记住,JAR 中的文件名区分大小写。