Saturday, June 28, 2008

How to zip a file using Java code?

Step-1:
We can create zip archives for files and folder contents using Java. All we need to do is to import “java.util.zip” namespace.

Step-2:
Then have to use the “ZipOutputStream” class and creating an object of that class will help us create a zip stream for creating the zip archive.

Step-3:
Then we need to read the files that are to be zipped in the byte stream format.

byte[] b = new byte[ (int)(cpFile.length()) ];
FileInputStream cpFileInputStream = new FileInputStream (cpFile);
cpFileInputStream.read(b, 0, (int)cpFile.length());



Step-4:
Now, we need to add the file to the zip archive as like writing into a file of type zipStream.


ZipEntry cpZipEntry = new ZipEntry(strZipEntryName);
cpZipOutputStream.putNextEntry(cpZipEntry);
cpZipOutputStream.write(b, 0, (int)cpFile.length());
cpZipOutputStream.closeEntry();


How to zip a folder now?
Now, we need to identify the source file type. For which we need to use “java.io” namespace.

Step-5:
Then to check the type of the source parameter, we can use like,

File cpFile = new File (strSource);
if(cpFile.isAbsolute())

System.out.println(strSource+ "is a absolute file");
else if(cpFile.isDirectory())

System.out.println(strSource+ "is a directory");
else if(cpFile.isFile())

System.out.println(strSource+ "is a simply file");
else if(cpFile.isHidden())

System.out.println(strSource+ "is a hidden file");
else
{
System.out.println("\nSource file/directory '"+strSource+ "'Not Found!");
return;
}

To check whether it is a directory
Step-5(a):
cpFile.isDirectory() returns a Boolean TRUE/FALSE value from which we can go ahead with the process.

Thats it! We've done. But this is not a complete part splitted. You can add your code part to add more spices for the zipped item to achieve.

No comments:

Powered By Blogger