Java: 如何从资源复制文件夹及其内容到临时目录?

huangapple go评论69阅读模式
英文:

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 文件夹的副本,以便我可以从该临时目录开始读取批处理文件和其他文件。

问题

当加载 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 {
    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());
            }
        }
    }
}

在这里,它只在临时目录中创建了 PMD 文件夹,没有复制任何内部文件和文件夹。有没有办法实现这一点?

英文:

Project structure:

src
|
|--resource
	|
	|--PMD
		|-pmd-bin
			|-test.bat
		|-report
			|-report.xml
	|
	|--staticresource

Using maven-assembly plugin, I am including the resources in the jar file.

As PMD folder will be used by the applcaition, I would like to create a copy of the PMD folder in the temp directory, so that I can start reading the bat files and other files from that temp directory.

ISSUE

When the jar loads, it fails to read the PMD folder inside resource.

Tried :

        InputStream pmdFolder = classLoader.getResourceAsStream(&quot;PMD&quot;);
InputStreamReader isr = new InputStreamReader(pmdFolder, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
List&lt;URL&gt; collect = br.lines().map(l -&gt; &quot;PMD&quot; + &quot;/&quot; + l)
.map(r -&gt; classLoader.getResource(r))
.collect(toList());
Path tempPMDFolder = null;
Path pmd = Files.createTempDirectory(&quot;PMD&quot;);
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(&quot;file -&gt; &quot;+file.getName());
if(file.isDirectory()){
Path tempPMDFolder = createTempPMDFolder(pmd, file.getName());
System.out.println(&quot;tempPMDFolder -&gt; &quot;+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());
}
}
}
}

Here it just creates the PMD folder in temp directory and nothing, inner files and folders are not copied. Any way we can achieve this?

答案1

得分: 0

以下是您提供的内容的中文翻译:

这是我想出来的东西。

将文件夹转换为 zip,并将该压缩文件放入资源中。
由于输入流只能通过文件进行读取。

InputStream pmdFolder = classLoader.getResourceAsStream("PMD.zip");
Path tempPMDDirectory = Files.createTempDirectory("PMD");

然后将zip内容提取到临时目录中,然后在整个应用程序中使用它。

if (pmdFolder != null) {
    try (ZipInputStream zipInputStream = new ZipInputStream(pmdFolder)) {
        // 提取zip内容并保存在临时目录中
        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("不良的zip条目");
            }

            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();
    }
}
英文:

Here is what I came up with.

Converted the folder to zip and put that zipped file in resources.
As inputstream can only read through a file.

InputStream pmdFolder = classLoader.getResourceAsStream(&quot;PMD.zip&quot;);
Path tempPMDDirectory = Files.createTempDirectory(&quot;PMD&quot;);

Then extracted the zip contents to the temp directory and then using that overall application.

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(&quot;Bad zip entry&quot;);
}
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();
}
}

huangapple
  • 本文由 发表于 2020年8月10日 20:33:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63340308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定