0

I've been facing an issues while copying the zip file(contains couple of RPM files) from resource folder to target folder using Spring boot application. It does create the zip file on target folder path but it doesn't have all the files inside and the one's created are corrupted. Please see attachment

I had gone through couple of links but seems solution is not working perfectly

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

Snapshot of Resource zip Folder [**Resource Path:**[2]

Snapshot of files inside zip Folder
package.zip files list

Code:

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

The above code create a zip file on target folder but its corrupted.When i try to open the file it gives me following error enter image description here

user1030128
  • 411
  • 9
  • 23

1 Answers1

0

Not sure why you think your code would produce a Zip file, you're just copying files into a file, which would just produce random bytes. You need to specifically create Zip files and ZipStreams. Here's a utility mehtod...

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

}
bluedevil2k
  • 9,366
  • 8
  • 43
  • 57
  • This part of mine is already working. i can add files in zip using above code. question is : How can i read zip file from resource folder and move into any target folder using spring boot? – user1030128 Sep 12 '19 at 00:14