-1

I am trying to write a spring boot java code to compress a Directory using REST API call. I find many codes using plain Java, but I am unable to find a one in Spring boot Java. I tried the below code and its zipping the file but when i try to zip the directory it throws FilenotFound Exception. Could anyone please help me with a working code. I dont know where I am going wrong. I am a beginner to Spring boot.

@RequestMapping(value="/zip", produces="application/zip")
public void zipFiles(HttpServletResponse response) throws IOException {
  response.setStatus(HttpServletResponse.SC_OK);
  response.addHeader("Content-Disposition", "attachment; filename=\"compressedfile.zip\"");
  ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
  ArrayList<File> files = new ArrayList<>();
  files.add(new File("C:\\Pavan\\zipfolder"));  //(zip is working if(C:\\Pavan\\zipfolder\\dockerfile.txt)
  for (File file : files) {
    zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
    FileInputStream fileInputStream = new FileInputStream(file);
    IOUtils.copy(fileInputStream, zipOutputStream);
    fileInputStream.close();
    zipOutputStream.closeEntry();
  }
zipOutputStream.close();
}

Error:

enter image description here

Olivier
  • 13,283
  • 1
  • 8
  • 24
Prathish
  • 61
  • 3
  • 10
  • can you check this answer ? [how to zip a folder itself using java](https://stackoverflow.com/questions/15968883/how-to-zip-a-folder-itself-using-java) – Yusuf Erdoğan Jul 29 '21 at 10:50
  • This is for Plain java code right. I have been given requirement on Compressing a Directory using Spring boot Java Rest API. Could you please share any reference for the same. – Prathish Jul 29 '21 at 10:57
  • Compressing a directory has nothing to do with Spring Boot or REST. It's just plain Java processing. – Olivier Jul 29 '21 at 11:20

1 Answers1

1

You are passing a directory to the FileInputStream constructor. This is not allowed, see Javadoc. Instead you have to iterate over the files contained in this directory. See Zipping and Unzipping in Java for an example.

slauth
  • 2,667
  • 1
  • 10
  • 18