【问题标题】:Copying zip File from application Resource folder to target using spring boot使用spring boot将zip文件从应用程序资源文件夹复制到目标
【发布时间】:2020-01-13 17:27:00
【问题描述】:

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

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

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

资源 zip 文件夹的快照 [

zip 文件夹内的文件快照

代码:

 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 文件,但它已损坏。当我尝试打开该文件时,它给了我以下错误

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

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

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

    【讨论】:

    • 我的这部分已经在工作了。我可以使用上面的代码在 zip 中添加文件。问题是:如何从资源文件夹中读取 zip 文件并使用 spring boot 移动到任何目标文件夹?
    猜你喜欢
    • 2020-01-31
    • 2017-03-31
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    相关资源
    最近更新 更多