no

How to zipped a file or directory in java

There are times when we have to zipped a file or directory recursively in Java. This is how we do it: public static void zipFile(File file...

There are times when we have to zipped a file or directory recursively in Java. This is how we do it:

public static void zipFile(File file) throws IOException {
 byte[] buffer = new byte[1024];

 FileOutputStream fos = new FileOutputStream(
   file.getParent() + File.separator + FilenameUtils.removeExtension(file.getName()) + ".zip");
 ZipOutputStream zos = new ZipOutputStream(fos);
 ZipEntry ze = new ZipEntry(file.getName());
 zos.putNextEntry(ze);
 FileInputStream in = new FileInputStream(file);

 int len;
 while ((len = in.read(buffer)) > 0) {
  zos.write(buffer, 0, len);
 }

 in.close();
 zos.closeEntry();

 // remember close it
 zos.close();
}

And now this is how we zipped a folder recursively:

public static void zipDir(File file) throws IOException {
 FileOutputStream fos = new FileOutputStream(new File(FilenameUtils.removeExtension(file.getParent() + File.separator + file.getName()) + ".zip"));
 ZipOutputStream zos = new ZipOutputStream(fos);
 FileUtils.addDirToArchive(getRootDir(), file.getPath(), zos);
 fos.flush();
 zos.close();
 fos.close();
}

public static void addDirToArchive(String relativeRoot, String dir2zip, ZipOutputStream zos) throws IOException {
 File zipDir = new File(dir2zip);
 String[] dirList = zipDir.list();
 byte[] readBuffer = new byte[2156];
 int bytesIn = 0;

 for (int i = 0; i < dirList.length; i++) {
  File f = new File(zipDir, dirList[i]);
  if (f.isDirectory()) {
   String filePath = f.getPath();
   addDirToArchive(relativeRoot, filePath, zos);
   continue;
  }

  FileInputStream fis = new FileInputStream(f);
  String relativePath = Paths.get(relativeRoot).relativize(f.toPath()).toString();
  ZipEntry anEntry = new ZipEntry(relativePath);
  zos.putNextEntry(anEntry);

  while ((bytesIn = fis.read(readBuffer)) != -1) {
   zos.write(readBuffer, 0, bytesIn);
  }

  fis.close();
 }
}

*FilenameUtils is from apache commons

Related

javaee-rest 7825112380906641850

Post a Comment Default Comments

item