java 通过代码从当前运行的 JAR 中提取文件

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

Extracting a file from the currently running JAR through code

javafilejarioextract

提问by Konstantin

Are there any built-in methods I can use to allow users to extract a file from the currently running JAR and save it on their disk?

是否有任何内置方法可以让用户从当前运行的 JAR 中提取文件并将其保存在他们的磁盘上?

Thanks in advance.

提前致谢。

采纳答案by Dave Newton

Use getResourceAsStream(docs), you can do whatever you want with it after that.

使用getResourceAsStream(docs),之后您可以随心所欲地使用它。

For a two-liner you could use one of the Commons IO copy methods.

对于两行,您可以使用Commons IO 复制方法之一

回答by Renato

File file = new File("newname.ext");
if (!file.exists()) {
     InputStream link = (getClass().getResourceAsStream("/path/resources/filename.ext"));
     Files.copy(link, file.getAbsoluteFile().toPath());
}

回答by GuruKulki

I am not sure whether you will get know from which jar your class is getting executed but you can try this to extract resources from jar : How to write a Java program which can extract a JAR file and store its data in specified directory (location)?

我不确定您是否会知道您的类是从哪个 jar 中执行的,但是您可以尝试从 jar 中提取资源: 如何编写一个可以提取 JAR 文件并将其数据存储在指定目录(位置)中的 Java 程序?