skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label Zip File. Show all posts
Showing posts with label Zip File. Show all posts
Saturday, October 13, 2012

File or Directory Zipper

Posted by Raju Gupta at 9:00 PM – 0 comments
 
This Program checks for the existance of the file or directory which is intended for zipping and does the zipping of the same. The user need to provide the location of the file or directory (mandatory) and the location to which it needs to be zipped (optional).

import java.io.*;
import java.util.zip.*;

public class zipUtil {
 public static void main(String a[]) {

  // Requires at least one param with a non-null value!

  if (a.length == 0) {
   System.err
     .println("Usage: filename with location is required and zipping location is optional");
   return;
  }

  try {

   String inputPath = a[0];
   String outPath;

   File file = new File(inputPath);
   boolean exists = file.exists(); // checks file existance
   String fname = file.getName();
   String absolutePath = file.getAbsolutePath(); // gets absolutepath
               // of the inputfile

   // gets inputfile's parent directory path to use incase extraction
   // location is not provided by enduser.
   String inputfilePath = absolutePath.substring(0,
     absolutePath.lastIndexOf(File.separator));

   if (exists) {
    // It returns false if File or directory does not exist
    System.out.println("the file or directory for zipping "
      + inputPath + " does exist");
   } else {
    // It returns true if File or directory exists
    System.out.println("the file or directory for zipping "
      + inputPath + " does not exist");
    throw new FileNotFoundException();
   }

   // checks for extraction location argument

   if (a.length == 2) {
    outPath = a[1];
   } else {
    outPath = inputfilePath;
   }

   if (!outPath.endsWith("/"))
    outPath += "/";

   File inFolder = new File(inputPath);
   File outFolder = new File(outPath + fname + ".zip");

   ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
     new FileOutputStream(outFolder)));
   BufferedInputStream in = null;
   byte[] data = new byte[1000];
   String files[] = inFolder.list();
   for (int i = 0; i < files.length; i++) {
    in = new BufferedInputStream(new FileInputStream(
      inFolder.getPath() + "/" + files[i]), 1000);
    out.putNextEntry(new ZipEntry(files[i]));
    int count;
    while ((count = in.read(data, 0, 1000)) != -1) {
     out.write(data, 0, count);
    }
    out.closeEntry();
   }
   out.flush();
   out.close();
  } catch (FileNotFoundException ioe) {
   System.err.println("this file not found");
   return;
  } catch (IOException ioe) {
   System.err.println("Unhandled exception:");
   ioe.printStackTrace();
   return;
  }
 }
}


[ Read More ]
Read more...
Wednesday, September 19, 2012

Java Zip file utilities

Posted by Admin at 9:26 AM – 0 comments
 

The java code provides various utility functions pertaining to Zipping and Compressing .


import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.zip.GZIPOutputStream;

import java.io.IOException;

public class ZipFileUtil {

   public ZipOutputStream createZipFile(String outFile,String[] files) {

        String zipFileName = outFile;
        byte[] buf = new byte[1024];

        try {

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));

            System.out.println("Archive:  " + zipFileName);

            // Compress the files
            for (int i=1; i<files.length; i++) {

FileInputStream in = new FileInputStream(files[i]);
                
                out.putNextEntry(new ZipEntry(files[i]));

                // Transfer bytes from the file to the ZIP file
                int len;
                while((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

                // Complete the entry
                out.closeEntry();
                in.close();

            }

            // Complete the ZIP file
            out.close();

    //Return Zip file
     return out; 

        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

   public void unzipFiles(String zipFileName) {

        try {

            ZipFile zf = new ZipFile(zipFileName);

            System.out.println("Archive:  " + zipFileName);
            
            // Enumerate each entry
            for (Enumeration entries = zf.entries(); 
entries.hasMoreElements();) {
                
                // Get the entry and its name
                ZipEntry zipEntry = 
(ZipEntry)entries.nextElement();
                String zipEntryName = zipEntry.getName();
                
                int lastDirSep;
           if ( (lastDirSep = zipEntryName.lastIndexOf('/'))>0) {
          String dirName = zipEntryName.substring(0, lastDirSep);
                    (new File(dirName)).mkdirs();
                }
                
                
                if (!zipEntryName.endsWith("/")) {
                    OutputStream out = new 
    FileOutputStream(zipEntryName);
                    InputStream in = zf.getInputStream(zipEntry);
                    
                    byte[] buf = new byte[1024];
                    int len;
                    while((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
    
                    // Close streams
                    out.close();
                    in.close();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

    }

  public void listFiles(String zipFileName) {

        try {

           System.out.println("Opening zip file " + zipFileName);
            ZipFile zf = new ZipFile(zipFileName);

            int counter = 0;

            // Enumerate each entry
        for (Enumeration entries = zf.entries(); 
entries.hasMoreElements();) {

                counter++;
                
                // Get the entry name
                String zipEntryName = 
((ZipEntry)entries.nextElement()).getName();
              }

        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

    }

   public GZIPOutputStream compressFile(String inFileName) {

        try {
        
          System.out.println("Creating the GZIP output stream.");
            String outFileName = inFileName + ".gz";
            GZIPOutputStream out = null;
            try {
                out = new GZIPOutputStream(new FileOutputStream(outFileName));
            } catch(FileNotFoundException e) {
             System.err.println("Could not create file: " + 
outFileName);
                System.exit(1);
            }
                    

            FileInputStream in = null;
            try {
                in = new FileInputStream(inFileName);
            } catch (FileNotFoundException e) {
             System.err.println("File not found. " + inFileName);
                System.exit(1);
            }

            //Transfering bytes from input file to GZIP Format
            byte[] buf = new byte[1024];
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();

            System.out.println("Completing the GZIP file");
            out.finish();
            out.close();
     return out;
        
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

    }

  public FileOutputStream uncompressFile(String inFileName) {

        try {

            if (!getExtension(inFileName).equalsIgnoreCase("gz")) {
                System.err.println("File name must have extension 
of ".gz"");
                System.exit(1);
            }

             GZIPInputStream in = null;
            try {
                in = new GZIPInputStream(new FileInputStream(inFileName));
            } catch(FileNotFoundException e) {
                System.err.println("File not found. " + 
inFileName);
                System.exit(1);
            }

            System.out.println("Open the output file.");
            String outFileName = getFileName(inFileName);
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(outFileName);
            } catch (FileNotFoundException e) {
                System.err.println("Could not write to file. " + 
outFileName);
                System.exit(1);
            }

//Transfering bytes from compressed file to the output file
            byte[] buf = new byte[1024];
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            System.out.println("Closing the file and stream");
            in.close();
            out.close();
     return out;
        
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

    }


[ Read More ]
Read more...
Monday, September 17, 2012

A basic Java code to search a file inside a zip file

Posted by Admin at 12:35 PM – 0 comments
 

This is a simple Java example to search for a file entry in a zip file.The java class uses java util zip package utilities for the same.


import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipFileSearcher {
 public static void main(String args[]) {

  try
  {
   // Read the zip file from location mentioned
   //If File not found throws IO Exception 

   ZipFile sourceZipFile = new ZipFile("c:/demo.zip"); 

   // Input file to search
   String filetoSearch = "getfile1.txt";
   Enumeration e = sourceZipFile.entries();
   boolean found = false;

   System.out.println("Searching " + filetoSearch + " in " + sourceZipFile.getName());

   // loop all the entries in the zip file
   while(e.hasMoreElements())
   {

    ZipEntry zipFile = (ZipEntry)e.nextElement();
    //validate zip file entry against the file to search
    if(zipFile.getName().toLowerCase().indexOf(filetoSearch) != -1)
    {

     found = true;
     // entry found condition
     System.out.println("File Found " + zipFile.getName());
     break;

    }

   }
   // entry not found condition
   if(found == false)
   {

    System.out.println("File :" + filetoSearch + " Not Found in Zip File: " + sourceZipFile.getName());
   }
   // close the source file
   sourceZipFile.close();


  }
  // handle IO exception
  catch(IOException ioe)

  {    System.out.println("Error opening zip file" + ioe);


  }

 }
}



[ Read More ]
Read more...

Uncompressing the file in the GZIP format

Posted by Admin at 12:03 PM – 0 comments
 

Sometimes it happens that when you download a file or any PDF file you get it in compressed mode. This means that the file is compressed, but can't read it in compressed form so, it needs to be uncompressed. There are various uncompress ion utility program which can be found very easily found on internet. If you are uncompressing a PDF with the extension .gz, then its resultant file will have a .PDF extension. Its main advantage is that it will uncompress the PDF file so that you can be able to read it. This utility is a part of java.util.zip package which provides classes and methods to compress and decompress the file.



import java.util.zip.GZIPInputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class JavaUncompress{
 public static void main(String args[]){
  try{
   //To Uncompress GZip File Contents we need to open the gzip file.....
   if(args.length<=0){
    System.out.println("Please enter the valid file name");
   }
   else{
    String inFilename = args[0];
    System.out.println("Opening the gzip file........

      .................. :  opened");


      GZIPInputStream gzipInputStream = null;
    FileInputStream fileInputStream = null;
    gzipInputStream = new GZIPInputStream(new 

      FileInputStream(inFilename));
    System.out.println("Opening the output file... : opened");
    String outFilename = inFilename +".pdf";
    OutputStream out = new FileOutputStream(outFilename);
    System.out.println("Transferring bytes from the compressed file to the output file........: Transfer successful");
    byte[] buf = new byte[1024];  //size can be changed according to programmer's need.
    int len;
    while ((len = gzipInputStream.read(buf)) > 0) {
     out.write(buf, 0, len);
    }
    System.out.println("The file and stream is ..

      ....closing.......... : closed"); 
      gzipInputStream.close();
    out.close();
   }
  }
  catch(IOException e){
   System.out.println("Exception has been thrown" + e);
  }
 }
}


[ Read More ]
Read more...
Sunday, September 16, 2012

Get Compression Method of Zip Entry using Java

Posted by Admin at 1:09 AM – 0 comments
 

Objective of this program is how to get compression method used to compress the entry using getMethod method of Java ZipEntry class.


import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
 
 
public class GetCompressionMethod {
 
        public static void main(String args[])
        {                
                try
                {
                   /* To Open a zip file, use ZipFile(String fileName) constructor of the ZipFile class. This constructor throws IOException for any I/O    error.*/


                   ZipFile zipFile = new ZipFile("D:/WebFiles.zip");

                   
                   /* Get list of zip entries using entries method of ZipFile class */

                   
                        Enumeration e = zipFile.entries();
                       
                        System.out.println("File Name\t\t\t\tCompression Method");
                        System.out.println("---------------------------------");
                       
                        while(e.hasMoreElements())
                        {
                                ZipEntry entry = (ZipEntry)e.nextElement();
                               
                                
   /* To get compression method used to compress entry, use int getMethod() method of ZipEntry class.This method returns the
    method of compression, or -1 if not specified.Compression method can be either STORED or DEFLATED for any zip entry.*/                              
                                 
                                 int method = entry.getMethod();
                                 
                                 if(method == ZipEntry.DEFLATED)
                                        System.out.println(entry.getName() + "\t\t\t\tDeflated");
                                 else if(method == ZipEntry.STORED)
                                        System.out.println(entry.getName() + "\t\t\t\tStored");
                                 else if(method == -1)
                                        System.out.println(entry.getName() + "\t\t\t\tNot Specified");
                                                               
                        }
                 
                         /* close the opened zip file using,void close() method.*/
                         
                          zipFile.close();
                       
                 }
                 catch(IOException ioe)
                 {
                        System.out.println("Error opening zip file" + ioe);
                 }
        }
 
}

[ Read More ]
Read more...

Get Number Of Entries In Zip File using Java

Posted by Admin at 1:07 AM – 0 comments
 

Objective of this program is how to open specified zip file and get number of entries (i.e. files and directories) inside opened zip file using size method of Java ZipFile class.


import Java.io.*;
import java.io.File;
import java.io.IOException;

import java.util.zip.ZipFile;
 
public class GetNumberOfFiles {
 
        public static void main(String args[])
        {
                 try
                 {
                        /*Open zip file using, ZipFile(String fileName) constructor of the ZipFile class.This constructor throws IOException for any I/O     error. */


                        ZipFile zipFile = new ZipFile("D:/WebFiles.zip");
 
                       
                        /*To get number of entries (i.e. files and directories) using,int size() method of ZipFile class.*/    

                         
                         int numberOfEntries = zipFile.size();
                         
                         System.out.println("There are ");
                         System.out.print(numberOfEntries);
                         System.out.print(" entries in zip file :");
                         System.out.print(zipFile.getName());  

                         
                        /*close the opened zip file using,void close()method.*/
                         
                         zipFile.close();
       
                 }
                 catch(IOException ioe)
                 {
                        System.out.println("Error opening zip file" + ioe);
                 }
        }
}

[ Read More ]
Read more...

Creating zip file using java

Posted by Admin at 12:02 AM – 0 comments
 

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class createZip {

        public static void main(String args[])
        {
                try
                {
                 //Providing input files with full path
                        String zipFile = "C:/Documents and Settings/468947/Desktop/a.zip";
                        String[] sourceFiles = {"C:/Documents and Settings/468947/Desktop/a.txt", "C:/Documents and Settings/468947/Desktop/b.txt"};
                        byte[] buffer = new byte[1024];
                         FileOutputStream fout = new FileOutputStream(zipFile);
                         ZipOutputStream zout = new ZipOutputStream(fout);
                         for(int i=0; i < sourceFiles.length; i++)
                         {
                                System.out.println("File given " + sourceFiles[i]);                  
                                FileInputStream fin = new FileInputStream(sourceFiles[i]);
                                //passing the files to ZipEntry 
                                
                                zout.putNextEntry(new ZipEntry(sourceFiles[i]));
                                int length;
                                while((length = fin.read(buffer)) > 0)
                                {
                                   zout.write(buffer, 0, length);
                                }
                                 zout.closeEntry();
                                 fin.close();
                         }
                          zout.close();
                          System.out.println("Zip file is  created successfully");
                }
                catch(IOException ioe)
                {
                        System.out.println("IOException :" + ioe);
                }
        }
}

[ Read More ]
Read more...
Saturday, September 15, 2012

Zip File Extraction | Java Example

Posted by Admin at 12:52 AM – 0 comments
 

It will exrect the contents of the compressed zip file and write the contents in a seperate file.


package Alltest; // package name where u create this class

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class xtractZipFile {

   
     // Extracts a zip file
    
    public void extractZipFile() {
        
        try {
            String zipFileName = "C:/Documents and Settings/313915/Desktop/Hi/Parent Satelitte report-FS.zip";
// Path of your compressed file
            String extractedFileName = "C:/Documents and Settings/313915/Desktop/Hi/extracted.doc"; 
// path where you want the file to be written
            
            //Create input and output stream
            ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
            OutputStream os = new FileOutputStream(extractedFileName);
            
            ZipEntry ze;
            
            byte[] buffer = new byte[1024];
            int nrBytesRead;
            
            
            if ((ze = zis.getNextEntry()) != null) {
             System.out.println(ze.getName());
                while ((nrBytesRead = zis.read(buffer)) > 0) {
                 os.write(buffer, 0, nrBytesRead);
                }
            }
                    
            // close the streams
            os.close();
            zis.close();
            System.out.println("File Extracted successfully!!!");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    

    public static void main(String[] args) {
        new xtractZipFile().extractZipFile();
    }
    
}

[ Read More ]
Read more...
Thursday, September 13, 2012

Preparing JAR and ZIP Files in Java

Posted by Admin at 2:10 PM – 0 comments
 

import java.util.zip.*;
import java.io.*;
 
public class ZipIt {
    public static void main(String args[]) throws IOException {
        if (args.length < 2) {
            System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
            System.exit(-1);
        }
        File zipFile = new File(args[0]);
        if (zipFile.exists()) {
            System.err.println("Zip file already exists, please try another");
            System.exit(-2);
        }
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        int bytesRead;
        byte[] buffer = new byte[1024];
        CRC32 crc = new CRC32();
        for (int i=1, n=args.length; i < n; i++) {
            String name = args[i];
            File file = new File(name);
            if (!file.exists()) {
                System.err.println("Skipping: " + name);
                continue;
            }
            BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(file));
            crc.reset();
            while ((bytesRead = bis.read(buffer)) != -1) {
                crc.update(buffer, 0, bytesRead);
            }
            bis.close();
            // Reset to beginning of input stream
            bis = new BufferedInputStream(
                new FileInputStream(file));
            ZipEntry entry = new ZipEntry(name);
            entry.setMethod(ZipEntry.STORED);
            entry.setCompressedSize(file.length());
            entry.setSize(file.length());
            entry.setCrc(crc.getValue());
            zos.putNextEntry(entry);
            while ((bytesRead = bis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesRead);
            }
            bis.close();
        }
        zos.close();
    }
}

[ Read More ]
Read more...
Tuesday, September 11, 2012

Open Zip File Using ZipFile Class Java Example

Posted by Admin at 11:25 AM – 0 comments
 
Open Zip File Using ZipFile Class Example This Java example shows how to open specified zip file using Java ZipFile class.

     
    import java.io.IOException;
    import java.util.zip.ZipFile;
     
    public class OpenZipFile {
           
            public static void main(String args[])
            {
                     
                     try
                     {
                            /*
                             * To Open a zip file, use
                             *
                             * ZipFile(String fileName)
                             * constructor of the ZipFile class.
                             *
                             * This constructor throws IOException for any I/O error.
                             */
                            ZipFile zipFile = new ZipFile("c:/FileIO/WebFiles.zip");
                           
                            /*
                             * Get the zip file name using,
                             *
                             * String getName()
                             * method of ZipFile class.
                             *
                             * This method returns path name of the zip file
                             */
                             System.out.println(zipFile.getName() + " Opened for reading!");
                             
                             /*
                              * close the opened zip file using,
                              * void close()
                              * method.
                              */
                             
                              zipFile.close();
                           
                     }
                     catch(IOException ioe)
                     {
                            System.out.println("Error opening zip file" + ioe);
                     }
            }
    }
     


Output of Above Java Program c:\FileIO\WebFiles.zip Opened for reading!
[ Read More ]
Read more...

Open Zip File From File Object Java Example

Posted by Admin at 11:23 AM – 0 comments
 
Open Zip File From File Object Example This Java example shows how to open specified zip file using File object.
     
    import java.io.File;
    import java.io.IOException;
    import java.util.zip.ZipFile;
     
    public class OpenZipFileFileObject {
           
            public static void main(String args[])
            {                
                     try
                     {
                           
                            /*
                             * Create file object for specified zip file.
                             */
                             
                             File file = new File("c:/FileIO/WebFiles.zip");
                             
                            /*
                             * To Open a zip file from File object, use
                             *
                             * ZipFile(File file)
                             * constructor of the ZipFile class.
                             *
                             * This constructor throws IOException for any I/O error.
                             */
                            ZipFile zipFile = new ZipFile(file);
                           
                            System.out.println(zipFile.getName() + " Opened for reading!");
                             
                             /*
                              * close the opened zip file using,
                              * void close()
                              * method.
                              */
                             
                              zipFile.close();
                           
                     }
                     catch(IOException ioe)
                     {
                            System.out.println("Error opening zip file" + ioe);
                     }
            }
    }
 

Output of Above Java Program c:\FileIO\WebFiles.zip Opened for reading!
[ Read More ]
Read more...
Monday, September 10, 2012

Get Specified Entry From Zip File Example

Posted by Admin at 1:39 PM – 0 comments
 
Get Specified Entry From Zip File Example. This Java example shows how to get specified entry (i.e. file or directory) using getEntry method of Java ZipFile class.

 
     
    import java.io.IOException;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
     
    public class GetSpecifiedEntry {
           
            public static void main(String args[])
            {
                     try
                     {
                            /*
                             * Open zip file using,
                             *
                             * ZipFile(String fileName)
                             * constructor of the ZipFile class.
                             *
                             * This constructor throws IOException for any I/O error.
                             */
                            ZipFile zipFile = new ZipFile("c:/FileIO/WebFiles.zip");
     
                            /*
                             * To get specified entry from opened zip file, use
                             *
                             * ZipEntry getEntry(String name)
                             * method of ZipFile class.
                             *
                             * This method returns entry specified by name, or null if
                             * not found.
                             */
                           
                            ZipEntry zipEntry = zipFile.getEntry("css/print.css");
                           
                            if(zipEntry != null)
                                    System.out.println("css/print.css found in Zip file");
                            else
                                    System.out.println("css/print.css not found in Zip file");
                           
                            /*
                             * PLEASE VISIT ZipEntry Examples for more details on
                             * how to process entries.
                             */
                     
                            /*
                             * close the opened zip file using,
                             * void close()
                             * method.
                             */
                             
                             zipFile.close();
           
                     }
                     catch(IOException ioe)
                     {
                            System.out.println("Error opening zip file" + ioe);
                     }
            }
    }
     
 


Output of Above Java Program
css/print.css found in Zip file
[ Read More ]
Read more...

Get Number Of Entries In Zip File Example

Posted by Admin at 1:37 PM – 0 comments
 
Get Number Of Entries In Zip File Example.
This Java example shows how to open specified zip
file and get number of entries (i.e. files and directories)
inside opened zip file using size method of Java ZipFile class.

    import java.io.IOException;
    import java.util.zip.ZipFile;
     
    public class GetNumberOfFiles {
     
            public static void main(String args[])
            {
                     try
                     {
                            /*
                             * Open zip file using,
                             *
                             * ZipFile(String fileName)
                             * constructor of the ZipFile class.
                             *
                             * This constructor throws IOException for any I/O error.
                             */
                            ZipFile zipFile = new ZipFile("c:/FileIO/WebFiles.zip");
     
                           
                            /*
                             * To get number of entries (i.e. files and directories)
                             * using,
                             *
                             * int size() method of ZipFile class.
                             *
                             */    
                             
                             int numberOfEntries = zipFile.size();
                             
                             System.out.println("There are ");
                             System.out.print(numberOfEntries);
                             System.out.print(" entries in zip file :");
                             System.out.print(zipFile.getName());  
                             
                            /*
                             * close the opened zip file using,
                             * void close()
                             * method.
                             */
                             
                             zipFile.close();
           
                     }
                     catch(IOException ioe)
                     {
                            System.out.println("Error opening zip file" + ioe);
                     }
            }
    }
     


Output of this program
There are
21 entries in zip file :c:\FileIO\WebFiles.zip

[ Read More ]
Read more...

Get All Entries From Zip File Example

Posted by Admin at 1:34 PM – 0 comments
 
Get All Entries From Zip File Example.
This Java example shows how to get enumeration of all entries
(i.e. files or directories) using entries method of
Java ZipFile class.

     
    import java.io.IOException;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
     
    public class GetAllEntries {
           
            public static void main(String args[])
            {
                     try
                     {
                            /*
                             * Open zip file using,
                             *
                             * ZipFile(String fileName)
                             * constructor of the ZipFile class.
                             *
                             * This constructor throws IOException for any I/O error.
                             */
                            ZipFile zipFile = new ZipFile("c:/FileIO/WebFiles.zip");
     
                            /*
                             * To get all entries from opened zip file, use
                             *
                             * Enumeration entries()
                             * method of ZipFile class.
                             *
                             * This method returns Enumeration of zip file entries.
                             */
                           
                            Enumeration e = zipFile.entries()                     
                            /*
                             * close the opened zip file using,
                             * void close()
                             * method.
                             */
                             
                             zipFile.close();
           
                     }
                     catch(IOException ioe)
                     {
                            System.out.println("Error opening zip file" + ioe);
                     }
            }
    }



[ Read More ]
Read more...

Find File in a Zip File Example

Posted by Admin at 1:20 PM – 0 comments
 
Find File in a Zip File Example.
This Java example shows how to find a particular file
in a zip file using ZipFile and ZipEntry Java classes.

    import java.io.IOException;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
     
    public class FindFileInZipFile {
           
            public static void main(String args[])
            {
                     try
                     {
                            //open the source zip file
                            ZipFile sourceZipFile = new ZipFile("c:/SearchDemo.zip");
                           
                            //File we want to search for inside the zip file
                            String searchFileName = "readme.txt";
     
                            //get all entries                      
                            Enumeration e = sourceZipFile.entries();
                            boolean found = false;
                           
                            System.out.println("Trying to search " + searchFileName + " in " + sourceZipFile.getName());
                           
                            while(e.hasMoreElements())
                            {
                                    ZipEntry entry = (ZipEntry)e.nextElement();
                                   
                                    /*
                                     * Here, normal compare would not work.
                                     *
                                     * Because zip might contain directories so the entry name will not
                                     * match extactly with the file name we want to search.
                                     *
                                     * Additionally, there might be more than one file with the same
                                     * name in different directories inside the zip archive.
                                     *
                                     * So approch here is to search using indexOf and not using
                                     * equals or equalsIgnoreCase methods.
                                     */
                                    if(entry.getName().toLowerCase().indexOf(searchFileName) != -1)
                                    {
                                            found = true;
                                            System.out.println("Found " + entry.getName());
                                           
                                            /*
                                             * if you want to search only first instance, uncomment the
                                             * following break statement.
                                             */
                                             
                                            //break;                       
                                    }
                            }
                           
                            if(found == false)
                            {
                                    System.out.println("File :" + searchFileName + " Not Found Inside Zip File: " + sourceZipFile.getName());
                            }
     
                            //close the zip file
                            sourceZipFile.close();
           
                     }
                     catch(IOException ioe)
                     {
                            System.out.println("Error opening zip file" + ioe);
                     }
            }
     
     
    }
     


Output of Above Java Program
Trying to search readme.txt in c:\SearchDemo.zip
Found xampplite/htdocs/drupal58/sites/all/README.txt
Found xampplite/htdocs/fun610/modules/README.txt
Found xampplite/htdocs/demo/sites/all/README.txt
Found xampplite/htdocs/fun610/themes/README.txt
Found xampplite/htdocs/knowledge/sites/all/README.txt

[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Java Example that generates General exceptions Like NullPointerException etc.
    Write a program that generates exceptions of type NullPointerException, NegativeArraySizeException, and IndexOutOfBoundsException. Record t...
  • Listing Files and Directory Using Java
    Lists Files and directory present in the system    File dir = new File("directoryName"); String[] children = dir.list(); ...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Java - Unknown Number of Parameters in Methods for JDK1.5
    The JVM identifies methods that can take different number of parameters using the three dots "..." in the method declaration and ...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Encryption using Bouncy Castle API
    code snippet for encrypting and decrypting strings in java. We will be using the Bouncy Castle API for this purpose and PaddedBufferedBlock...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Java Class to Calculate the Volume of Box
    Here is a Java Class to Calculate the Volume of Box. class Box { double width; double height; double depth; // This is the con...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger