import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zipping {
public static void main(String[] a) throws Exception {
BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter the source directory/file name : ");
String source = in.readLine().trim();
File src = new File (source);
if (src.isDirectory()) {
String zipFile = source + ".zip";
zipFolder (source, zipFile);
} else {
int lastDot = source.lastIndexOf(".");
String zipFile;
if (lastDot != -1) {
zipFile = source.substring(0, lastDot) + ".zip";
} else {
zipFile = source + ".zip";
}
zipFolder (source, zipFile);
}
}
static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFileToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws
Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
throws Exception {
//if ( src.isDirectory()) {
File folder = new File(srcFolder);
String[] fileName = folder.list();
for (int i = 0; i < fileName.length; i++) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName[i], zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName[i],
zip);
}
}
}
}
Java 把文件/目錄壓縮成zip文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
Java 字符串(二)
woshiwangdao
2020-07-01 19:05:12
synchronized 修飾方法和修飾代碼塊的區別
陈蒙_
2020-06-16 08:43:46
Spring資源訪問器
shuijieshuijie
2020-06-15 18:47:04
Java學習 - Thread Synchronized (一)
Eric_WMX
2020-02-25 12:26:22
解壓文件 Unzip
jeff2007
2020-02-24 13:45:49
修改 ibatis 分頁機制(ORACLE物理分頁)
jeff2007
2020-02-24 13:45:49
java中抽象枚舉類
小紫怡宝宝
2020-02-22 15:22:29
java線程(一)
woshiwangdao
2020-02-22 08:32:49
Java線程(二)
woshiwangdao
2020-02-22 08:32:49
Java 輸入輸出流(一)
woshiwangdao
2020-02-22 08:32:49
Java線程互斥(三)
woshiwangdao
2020-02-22 08:32:49
java 生產者消費者問題
woshiwangdao
2020-02-22 08:32:49
Java 數組
woshiwangdao
2020-02-22 08:32:49
字符串(一)
woshiwangdao
2020-02-22 08:32:49