简体   繁体   English

java:如何将 jar 文件中的目录复制到 tmp 目录?

[英]java: How to copy a directory in a jar file to a tmp dir?

I know how to create a temporary directory in Java, but is there an easy way to copy files in Java from the jar file to this directory?我知道如何在 Java 中创建一个临时目录,但是有没有一种简单的方法可以将 Java 中的文件从 jar 文件复制到此目录?

File tmpDir = new File(System.getProperty("java.io.tmpdir"));
File helpDir = new File(tmpDir, "myApp-help");
helpDir.createNewFile(); // oops, this isn't right, I want to create a dir
URL helpURL = getClass().getResource("/help-info");  

/* ???? I want to copy the files from helpURL to helpDir */

Desktop desktop = Desktop.getDesktop();
URI helpURI = /* some URI from the new dir's index.html */
desktop.browse(helpURI);

Apache's org.apache.commons.io.FileUtils can do that for you Apache 的org.apache.commons.io.FileUtils可以为您做到这一点

To create directory use File.mkdir();创建目录使用File.mkdir();

Convert URL to File with org.apache.commons.io.FileUtils.toFile(URL)使用org.apache.commons.io.FileUtils.toFile(URL)将 URL 转换为文件

use org.apache.commons.io.FileUtils.copyFile() to copy.使用org.apache.commons.io.FileUtils.copyFile()进行复制。

You can make use of the command jar tf [here your jarfile] .您可以使用命令jar tf [here your jarfile] This will list the contents of the JAR Archive with their full path, relative to the jarfile (1 line = 1 file).这将列出 JAR 存档的内容及其完整路径,相对于 jarfile(1 行 = 1 个文件)。 Check if the line starts with the path of the directory you want to extract, and use Class.getResourceAsStream(URL) for the matching lines and extract them to your temporary folder.检查该行是否以您要提取的目录的路径开头,并使用Class.getResourceAsStream(URL)匹配行并将它们提取到您的临时文件夹。

Here is an example output of jar tf :这是jar tf的示例 output :

META-INF/MANIFEST.MF
TicTacToe.class
audio/
audio/beep.au
audio/ding.au
audio/return.au
audio/yahoo1.au
audio/yahoo2.au
images/
images/cross.gif
images/not.gif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM