YChalk

ZipFileManager

Apr 8th, 2021 (edited)
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1. public class ZipFileManager {
  2.  
  3.     private Path zipFile;
  4.  
  5.     public ZipFileManager(Path zipFile) {
  6.         this.zipFile = zipFile;
  7.     }
  8.  
  9.     public void createZip(Path source) throws Exception{
  10.         if (!Files.exists(zipFile.getParent())){
  11.             Files.createDirectories(zipFile.getParent());
  12.         }
  13.  
  14.         try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile))) {
  15.             if (Files.isRegularFile(source)) {
  16.                 addNewZipEntry(zipOutputStream, source.getParent(), source.getFileName());
  17.             }
  18.             else if (Files.isDirectory(source)){
  19.                 FileManager fileManager = new FileManager(source);
  20.                 List<Path> fileNames = fileManager.getFileList();
  21.                 for (Path path : fileNames){
  22.                     addNewZipEntry(zipOutputStream, path.getParent(), path);
  23.                 }
  24.             }
  25.             else {
  26.                 throw new PathNotFoundException();
  27.             }
  28.             /*ZipEntry zipEntry = new ZipEntry(source.getFileName().toString());
  29.             zipOutputStream.putNextEntry(zipEntry);
  30.  
  31.             try (InputStream inputStream = Files.newInputStream(source)) {
  32.  
  33.                 while (inputStream.available() > 0) {
  34.                     zipOutputStream.write(inputStream.read());
  35.                 }
  36.             }*/
  37.         }
  38.     }
  39.  
  40.     private void addNewZipEntry(ZipOutputStream zipOutputStream, Path filePath, Path fileName) throws Exception{
  41.         try(InputStream inputStream = Files.newInputStream(filePath.resolve(fileName))) {
  42.             ZipEntry zipEntry = new ZipEntry(fileName.toString());
  43.             zipOutputStream.putNextEntry(zipEntry);
  44.  
  45.             copyData(inputStream, zipOutputStream);
  46.             /*while (inputStream.available() > 0) {
  47.                 zipOutputStream.write(inputStream.read());
  48.             }*/
  49.             zipOutputStream.closeEntry();
  50.         }
  51.     }
  52.  
  53.     private void copyData(InputStream in, OutputStream out) throws Exception{
  54.         while (in.available() > 0){
  55.             out.write(in.read());
  56.         }
  57.     }
  58. }
  59.  
Add Comment
Please, Sign In to add comment