gpt4 book ai didi

java - 使用 Spring Boot 将 zip 文件从应用程序资源文件夹复制到目标

转载 作者:行者123 更新时间:2023-12-02 00:46:06 28 4
gpt4 key购买 nike

使用Spring boot应用程序将zip文件(包含几个RPM文件)从资源文件夹复制到目标文件夹时,我遇到了问题。它确实在目标文件夹路径上创建了 zip 文件,但其中没有包含所有文件,并且创建的文件已损坏。请参阅附件

我浏览了几个链接,但似乎解决方案运行不完美

  1. How to get files from resources folder. Spring Framework
  2. Read file from resources folder in Spring Boot

资源 zip 文件夹的快照[**Resource Path:**[2]

zip 文件夹内文件的快照
<强> package.zip files list

代码:

 ClassPathResource cpr = null;
cpr = new ClassPathResource("/16.00/package.zip");
try {
InputStream data = cpr.getInputStream();
File targetFile = new File("C:\\package.zip");
java.nio.file.Files.copy(
data,
targetFile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
IOUtils.closeQuietly(data);
log.info("w"+data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

上面的代码在目标文件夹上创建了一个 zip 文件,但它已损坏。当我尝试打开该文件时,出现以下错误 enter image description here

最佳答案

不确定为什么您认为您的代码会生成 Zip 文件,您只是将文件复制到文件中,这只会生成随机字节。您需要专门创建 Zip 文件和 ZipStream。这是一个实用方法...

public static void addToZipFile(String zipFile, String[] filesToZip) throws Exception 
{
// Create a buffer for reading the files
byte[] buf = new byte[1024];

// Create the ZIP file
String outFilename = zipFile;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));

// Compress the files
for (int i = 0; i < filesToZip.length; i++)
{
FileInputStream in = new FileInputStream(filesToZip[i]);

// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(FilenameUtils.getName(filesToZip[i])));

// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}

// Complete the entry
out.closeEntry();
in.close();
}

// Complete the ZIP file
out.close();

}

关于java - 使用 Spring Boot 将 zip 文件从应用程序资源文件夹复制到目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57896473/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com