Saturday, July 12, 2014

Zip File Handling with Java And Selenium WebDriver

Some time we need to compress files for sending it.Here we learn how we can handle this programmatically.

We can handle this in two ways
1. Java SDK
2. Selenium WebDriver

1.Zip Using Java SDK:

public class Compress {

static List<String> fileList=new ArrayList<String>();

public static void main(String args[]) throws IOException {
        sendToZip(new File("Our Source To Zip"), new File("Our Destination To Zip\\ZipFile.ZIP"));
}

##########################################
#This Method is Created for List down Of All Files
# within the Source Path and put the Absolute Path 
#into the List
##########################################
    private static List<String> addFiletoList(File inputDir)
    {
        File[] listOfFile=inputDir.listFiles();
        for (File file : listOfFile) {
        if(file.isFile())
            fileList.add(file.getAbsolutePath());
        else
            addFiletoList(file);
        }
    return fileList;    
    }


##########################################
#This Method is Created to Zip the all File and 
#Save it to the Destination Path
###########################################
    private  static void sendToZip(File zipInput,File zipOutPut) throws FileNotFoundException, IOException
    {  
        List<String> fileList=new ArrayList<String>();
        fileList=addFiletoList(zipInput);
        FileOutputStream fos=new FileOutputStream(zipOutPut);
        ZipOutputStream zos=new ZipOutputStream(fos);
        for(String filePath:fileList){
            FileInputStream fis = new FileInputStream(filePath);

           
            //String name is required for showing the file name after zip same as before zip
 
            String name = filePath.substring(zipInput.getAbsolutePath().length()+1, filePath.length());
            ZipEntry entry = new ZipEntry(name);
            zos.putNextEntry(entry);

            int len;
            byte[] buffer = new byte[4096];
            while ((len = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, len);
            }

            fis.close();
            zos.closeEntry();
        }
        zos.close();
        fos.close();
    }



 1.Zip Using Selenium WebDriver:

Zip compress=new Zip();compress.zip(new File("Our Source To Zip"), new File("Our Destination To Zip"));





Now we can see that Zip using Selenium is more compact and easy coding but there is a problem if source and destination zip folder path is same then it creates a corrupted zip folder with in our zip folder.

So always keep in mind if we use selenium provided zip functionality then Zip folder Source and Zip folder Destination should be different. 

No comments:

Post a Comment