How To Zipped A File Or Directory Inwards Java

There are times when nosotros convey to zipped a file or directory recursively inward Java. This is how nosotros create it:

public static void zipFile(File file) throws IOException {  byte[] buffer = novel byte[1024];   FileOutputStream fos = novel FileOutputStream(    file.getParent() + File.separator + FilenameUtils.removeExtension(file.getName()) + ".zip");  ZipOutputStream zos = novel ZipOutputStream(fos);  ZipEntry ze = novel ZipEntry(file.getName());  zos.putNextEntry(ze);  FileInputStream inward = novel FileInputStream(file);   int len;  spell ((len = in.read(buffer)) > 0) {   zos.write(buffer, 0, len);  }   in.close();  zos.closeEntry();   // shout upwards closed it  zos.close(); }

And right away this is how nosotros zipped a folder recursively:

public static void zipDir(File file) throws IOException {  FileOutputStream fos = novel FileOutputStream(new File(FilenameUtils.removeExtension(file.getParent() + File.separator + file.getName()) + ".zip"));  ZipOutputStream zos = novel ZipOutputStream(fos);  FileUtils.addDirToArchive(getRootDir(), file.getPath(), zos);  fos.flush();  zos.close();  fos.close(); }  populace static void addDirToArchive(String relativeRoot, String dir2zip, ZipOutputStream zos) throws IOException {  File zipDir = novel File(dir2zip);  String[] dirList = zipDir.list();  byte[] readBuffer = novel byte[2156];  int bytesIn = 0;   for (int i = 0; i < dirList.length; i++) {   File f = novel File(zipDir, dirList[i]);   if (f.isDirectory()) {    String filePath = f.getPath();    addDirToArchive(relativeRoot, filePath, zos);    continue;   }    FileInputStream fis = novel FileInputStream(f);   String relativePath = Paths.get(relativeRoot).relativize(f.toPath()).toString();   ZipEntry anEntry = novel ZipEntry(relativePath);   zos.putNextEntry(anEntry);    spell ((bytesIn = fis.read(readBuffer)) != -1) {    zos.write(readBuffer, 0, bytesIn);   }    fis.close();  } } 

*FilenameUtils is from apache commons
Next
Previous
Click here for Comments

0 komentar:

Please comment if there are any that need to be asked.