Showing posts with label creating zip file in java. Show all posts
Showing posts with label creating zip file in java. Show all posts

Thursday, February 20

Creating a zip file in java

Creating a zip file in java 




Converting a String into a test file and putting that in zip file 


  1. Here I am creating File.zip file at location D:/file.zip
  2. Here two text files are using by reading an existing txt file
  3. One Pdf file is created by reading an existing file
  4. One txt file is created from a String 
  5. All are zipped together and are put in zip file 




import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class Zipper {
    
    public static void main( String[] args )
    {
      byte[] buffer = new byte[1024];

      try{

        FileOutputStream fos = new FileOutputStream("D:\\File.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze= new ZipEntry("spy.txt");
        zos.putNextEntry(ze);
        FileInputStream in = new FileInputStream("D:\\spy.txt");

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

        in.close();
        
        ZipEntry ze1= new ZipEntry("spy1.txt");
        zos.putNextEntry(ze1);
        FileInputStream in1 = new FileInputStream("D:\\spy.txt");

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

        in1.close();
        
        ZipEntry ze2= new ZipEntry("Promote PDF.pdf");
        zos.putNextEntry(ze2);
        FileInputStream in2 = new FileInputStream("C:/Users/mkum63/Desktop/Promote PDF.pdf");

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

        in.close();
        
        
        ZipEntry ze4= new ZipEntry("spy4.txt");
        zos.putNextEntry(ze4);
        StringBuilder sb=new StringBuilder();
        sb.append("dfdgfdgf");
        sb.append("\n");
        sb.append("dsfsdfs");
        sb.append("/n");
        sb.append("dsfsfsdfdffdf");

        InputStream  in4 = new ByteArrayInputStream(sb.toString().getBytes());
                
        int len4;
        while ((len4 = in4.read(buffer))>0) {
          zos.write(buffer, 0, len4);
        }
          
        in4.close();
        
        zos.closeEntry();

        zos.close();

        System.out.println("Done");

      }catch(IOException ex){
         ex.printStackTrace();
      }
    }
}