Create ZIP file in java
ZipFileExample.java
package pack;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFileExample {
// private static final String INPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.txt";
private static final String INPUT_FILE="D:\\Raju\\Test.txt";
//private static final String OUTPUT_FILE = "C:\\Users\\nikos\\Desktop\\TestFiles\\testFile.zip";
private static final String OUTPUT_FILE = "D:\\Raju\\Test.zip";
public static void main(String[] args) {
zipFile(new File(INPUT_FILE), OUTPUT_FILE);
}
public static void zipFile(File inputFile, String zipFilePath) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
ZipEntry zipEntry = new ZipEntry(inputFile.getName());
zipOutputStream.putNextEntry(zipEntry);
FileInputStream fileInputStream = new FileInputStream(inputFile);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buf)) > 0) {
zipOutputStream.write(buf, 0, bytesRead);
}
// close ZipEntry to store the stream to the file
zipOutputStream.closeEntry();
zipOutputStream.close();
fileOutputStream.close();
System.out.println("File :" + inputFile.getCanonicalPath()+" is zipped to archive :"+zipFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
0 comments:
Post a Comment