Showing posts with label folder. Show all posts
Showing posts with label folder. Show all posts

Thursday, November 24, 2016

Unzip files using Java

We will unzip a zip file with Java using a third party library. But yes, you can also unzip the zip using pure Java without any third party library.

Language Used:
Java

Git Repo:
https://cooltrickshome.blogspot.in/2016/11/unzip-files-using-java.html

Reference:

Without using any third party: http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java

Using Third party library : http://stackoverflow.com/questions/10633595/java-zip-how-to-unzip-folder

POM Dependency:
 <!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->  
 <dependency>  
   <groupId>net.lingala.zip4j</groupId>  
   <artifactId>zip4j</artifactId>  
   <version>1.3.1</version>  
 </dependency>  

Program:

Main method:
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           Scanner s=new Scanner(System.in);  
           System.out.println("Please enter the zip file to be unzipped");  
           String zipFile=s.nextLine();  
           System.out.println("Please enter the password for zip file (type none if no password)");  
           String password=s.nextLine();  
           File f=new File(zipFile);  
           //Your password if any  
           unzipFile(zipFile, f.getParent(),password);  
           System.out.println("Extracted zip content at "+f.getParent());  
           s.close();  
      }  

How it works:
1) We make a scanner object to take user input
2) We ask user the file to be zipped
3) We ask password from user if needed
4) We call unzipFile method which unzip the file. It take 3 parameters.
5) First param defines the file to be unzipped
6) Second param defines the path where file will be extracted
7) Third param defines the password to be used for extracting zip file

unzipFile method:
      public static void unzipFile(String sourceZip, String destination, String password)  
      {  
           try {  
             ZipFile zipFile = new ZipFile(sourceZip);  
             if (zipFile.isEncrypted()) {  
               zipFile.setPassword(password);  
             }  
             zipFile.extractAll(destination);  
           } catch (ZipException e) {  
             e.printStackTrace();  
           }  
      }  

How it works:
1) We make an object of ZipFile pointing to the zip file to be unzipped
2) isEncrypted tell if the zip file require password for extraction
3) If password is needed we use setPassword to set the password for extraction
4) extractAll retreives the content of the zip file

Output:
 Please enter the zip file to be unzipped  
 C:\Users\anurag\Desktop\images.zip  
 Please enter the password for zip file (type none if no password)  
 Your password if any  
 Extracted zip content at C:\Users\anurag\Desktop  

Full Program:
 package com.cooltrickshome;  
 import java.io.File;  
 import java.util.Scanner;  
 import net.lingala.zip4j.core.ZipFile;  
 import net.lingala.zip4j.exception.ZipException;  
 public class UnzipFile {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           Scanner s=new Scanner(System.in);  
           System.out.println("Please enter the zip file to be unzipped");  
           String zipFile=s.nextLine();  
           System.out.println("Please enter the password for zip file (type none if no password)");  
           String password=s.nextLine();  
           File f=new File(zipFile);  
           //Your password if any  
           unzipFile(zipFile, f.getParent(),password);  
           System.out.println("Extracted zip content at "+f.getParent());  
           s.close();  
      }  
      public static void unzipFile(String sourceZip, String destination, String password)  
      {  
           try {  
             ZipFile zipFile = new ZipFile(sourceZip);  
             if (zipFile.isEncrypted()) {  
               zipFile.setPassword(password);  
             }  
             zipFile.extractAll(destination);  
           } catch (ZipException e) {  
             e.printStackTrace();  
           }  
      }  
 }  

Hope it helps :)

Wednesday, November 23, 2016

Zip Folder using Java

You can zip your folders/files using Java

Language Used:
Java

Git Repo:
https://github.com/csanuragjain/extra/tree/master/Compression/Zip%20Folder

Reference:

Without any third party library : http://www.java2s.com/Code/Java/File-Input-Output/UseJavacodetozipafolder.htm

Using third party library: http://howtodoinjava.com/core-java/io/how-to-create-password-protected-zip-files-in-java/

Program:

Main method:
      public static void main(String[] a) throws Exception {  
           Scanner s = new Scanner(System.in);  
           System.out.println("Enter the file/folder to be zipped");  
           String zipFile = s.nextLine();  
           File f = new File(zipFile);  
           String zipFileName = f.getName() + ".zip";  
           if (f.isDirectory()) {  
                zipFolder(zipFile, zipFileName);  
           } else {  
                zipFile(zipFile, zipFileName);  
           }  
           System.out.println(zipFileName + " has been generated at "  
                     + new File("").getAbsolutePath());  
           s.close();  
      }  

How it works:
1) First we ask user the folder or file to be zipped.
2) We check if the given is file or folder
3) If it is file we call zipFile method passing the file to be zipped
4) If it is directory we call zipFolder method passing the folder to be zipped

zipFile Method:
      static public void zipFile(String srcFile, String destZipFile)  
                throws Exception {  
           ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(destZipFile));  
           File folder = new File(srcFile);  
           byte[] buf = new byte[1024];  
           int len;  
           FileInputStream in = new FileInputStream(srcFile);  
           zip.putNextEntry(new ZipEntry(folder.getName()));  
           while ((len = in.read(buf)) > 0) {  
                zip.write(buf, 0, len);  
           }  
           zip.close();  
      }  

How it works:
1) We make a zipoutputstream object pointing to the destination zip file to be created
2) We make a File object pointing to the source file to be zipped
3) We start reading the source file using read method and write it in the zip object made in step1
4) Finally our file is zipped

zipFolder method:
      static public void zipFolder(String srcFolder, String destZipFile)  
                throws Exception {  
           ZipOutputStream zip = null;  
           FileOutputStream fileWriter = null;  
           fileWriter = new FileOutputStream(destZipFile);  
           zip = new ZipOutputStream(fileWriter);  
           addFolderToZip("", srcFolder, zip);  
           zip.flush();  
           zip.close();  
      }  

How it works:
1) We make an object of zipoutputstream pointing to the destination zip file to be written
2) We call addFolderToZip method passing 3 argument
3) First argument defines the parent. So for example if we want to zip a.txt which was present within folder abc then first argument will be abc. For the first time parent would be ""
4) Second argument defines the source folder to be zipped
5) Third argument is the object pointing to output zip file to be written.

addFolderToZip method:
      static private void addFolderToZip(String path, String srcFolder,  
                ZipOutputStream zip) throws Exception {  
           File folder = new File(srcFolder);  
           for (String fileName : folder.list()) {  
                if (path.equals("")) {  
                     addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);  
                } else {  
                     addFileToZip(path + "/" + folder.getName(), srcFolder + "/"  
                               + fileName, zip);  
                }  
           }  
      }  

How it works:
1) We iterate through each of files/folder present in the source folder to be zipped
2) For each of the file/folder scanned if it does not have parent then path is "" otherwise path has some value
3) To understand path, we take an example assume user gave c:\abc folder to be zipped. C:\abc has a folder named b and b folder has a file named c.txt. So when c.txt comes to this method then path will be b which is the parent. Similarly when b folder comes to zip the parent is null so path will be ""

addFileToZip method:
      static private void addFileToZip(String path, String srcFile,  
                ZipOutputStream zip) throws Exception {  
           File folder = new File(srcFile);  
           if (folder.isDirectory()) {  
                addFolderToZip(path, srcFile, zip);  
           } else {  
                byte[] buf = new byte[1024];  
                int len;  
                FileInputStream in = new FileInputStream(srcFile);  
                zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));  
                while ((len = in.read(buf)) > 0) {  
                     zip.write(buf, 0, len);  
                }  
           }  
      }  

How it works:
1) We make a file object pointing to the source file/folder to be zipped.
2) If its is directory we call addFolderToZip method to get entries within it
3)Otherwise if it is file then we write it in the zip

Output:
 Enter the file/folder to be zipped  
 C:\Users\anurag\Desktop\images  
 images.zip has been generated at C:\Users\anurag\Desktop\zipfolder

Full Program:
 package com.cooltrickshome;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.util.Scanner;  
 import java.util.zip.ZipEntry;  
 import java.util.zip.ZipOutputStream;  
 public class ZipFolder {  
      public static void main(String[] a) throws Exception {  
           Scanner s = new Scanner(System.in);  
           System.out.println("Enter the file/folder to be zipped");  
           String zipFile = s.nextLine();  
           File f = new File(zipFile);  
           String zipFileName = f.getName() + ".zip";  
           if (f.isDirectory()) {  
                zipFolder(zipFile, zipFileName);  
           } else {  
                zipFile(zipFile, zipFileName);  
           }  
           System.out.println(zipFileName + " has been generated at "  
                     + new File("").getAbsolutePath());  
           s.close();  
      }  
      static public void zipFile(String srcFile, String destZipFile)  
                throws Exception {  
           ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(destZipFile));  
           File folder = new File(srcFile);  
           byte[] buf = new byte[1024];  
           int len;  
           FileInputStream in = new FileInputStream(srcFile);  
           zip.putNextEntry(new ZipEntry(folder.getName()));  
           while ((len = in.read(buf)) > 0) {  
                zip.write(buf, 0, len);  
           }  
           zip.close();  
      }  
      static public void zipFolder(String srcFolder, String destZipFile)  
                throws Exception {  
           ZipOutputStream zip = null;  
           FileOutputStream fileWriter = null;  
           fileWriter = new FileOutputStream(destZipFile);  
           zip = new ZipOutputStream(fileWriter);  
           addFolderToZip("", srcFolder, zip);  
           zip.flush();  
           zip.close();  
      }  
      static private void addFileToZip(String path, String srcFile,  
                ZipOutputStream zip) throws Exception {  
           File folder = new File(srcFile);  
           if (folder.isDirectory()) {  
                addFolderToZip(path, srcFile, zip);  
           } else {  
                byte[] buf = new byte[1024];  
                int len;  
                FileInputStream in = new FileInputStream(srcFile);  
                zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));  
                while ((len = in.read(buf)) > 0) {  
                     zip.write(buf, 0, len);  
                }  
           }  
      }  
      static private void addFolderToZip(String path, String srcFolder,  
                ZipOutputStream zip) throws Exception {  
           File folder = new File(srcFolder);  
           for (String fileName : folder.list()) {  
                if (path.equals("")) {  
                     addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);  
                } else {  
                     addFileToZip(path + "/" + folder.getName(), srcFolder + "/"  
                               + fileName, zip);  
                }  
           }  
      }  
 }  

Hope it helps :)