[英]Java : How to copy folder with contents from resource and copy to temp directory?
项目结构:
src
|
|--resource
|
|--PMD
|-pmd-bin
|-test.bat
|-report
|-report.xml
|
|--staticresource
使用maven-assembly
插件,我将资源包含在 jar 文件中。
由于应用程序将使用 PMD 文件夹,我想在临时目录中创建 PMD 文件夹的副本,以便我可以开始从该临时目录中读取 bat 文件和其他文件。
问题
当 jar 加载时,它无法读取资源内的 PMD 文件夹。
试过:
InputStream pmdFolder = classLoader.getResourceAsStream("PMD");
InputStreamReader isr = new InputStreamReader(pmdFolder, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
List<URL> collect = br.lines().map(l -> "PMD" + "/" + l)
.map(r -> classLoader.getResource(r))
.collect(toList());
Path tempPMDFolder = null;
Path pmd = Files.createTempDirectory("PMD");
for (URL url : collect) {
System.out.println(url.toString());
createSameTempStructure(url, pmd);
}
private static void createSameTempStructure(URL url, Path pmd) throws IOException {
//tempPMDFolder.toFile().deleteOnExit();
try(final InputStream is = url.openStream()) {
File file = FileUtils.toFile(url);
System.out.println("file -> "+file.getName());
if(file.isDirectory()){
Path tempPMDFolder = createTempPMDFolder(pmd, file.getName());
System.out.println("tempPMDFolder -> "+tempPMDFolder.toString());
FileUtils.copyDirectory(file, tempPMDFolder.toFile());
} else {
try (OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(is, outputStream);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
在这里,它只是在 temp 目录中创建 PMD 文件夹,没有任何内容,内部文件和文件夹不会被复制。 我们有什么办法可以做到这一点?
这是我想出的。
将文件夹转换为zip
并将该压缩文件放入资源中。 由于输入流只能读取文件。
InputStream pmdFolder = classLoader.getResourceAsStream("PMD.zip");
Path tempPMDDirectory = Files.createTempDirectory("PMD");
然后将 zip 内容提取到临时目录,然后使用整个应用程序。
if (pmdFolder != null) {
try (ZipInputStream zipInputStream = new ZipInputStream(pmdFolder)) {
// Extract the zip contents and keep in temp directory
extract(zipInputStream, tempPMDDirectory.toFile());
}
}
public static void extract(ZipInputStream zip, File target) throws IOException {
try {
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
File file = new File(target, entry.getName());
if (!file.toPath().normalize().startsWith(target.toPath())) {
throw new IOException("Bad zip entry");
}
if (entry.isDirectory()) {
file.mkdirs();
continue;
}
byte[] buffer = new byte[BUFFER_SIZE];
file.getParentFile().mkdirs();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
int count;
while ((count = zip.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
out.close();
}
} finally {
zip.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.