使用java.util.zip壓縮、解壓文件
壓縮文件:
import java.util.zip.*;
import java.io.*;
public class ZipTest {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("請輸入參數:javac ZipTest 需壓縮的文件名及路徑 保存的文件名及路徑。(e.g. c:/test.txt)");
} else {
ZipCompressor compressor = new ZipCompressor();
boolean isSuccessful= compressor.zipCompress(args, args[args.length - 1]);
if (isSuccessful) {
System.out.println("文件壓縮成功。");
} else {
System.out.println("文件壓縮失敗。");
}
}
}
}
class ZipCompressor {
public ZipCompressor() {}
/**@param srcFiles 需壓縮的文件路徑及文件名
* @param desFile 保存的文件名及路徑
* @return 如果壓縮成功返回true
*/
public boolean zipCompress(String[] srcFiles, String desFile) {
boolean isSuccessful = false;
String[] fileNames = new String[srcFiles.length-1];
for (int i = 0; i < srcFiles.length-1; i++) {
fileNames[i] = parse(srcFiles[i]);
}
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFile));
ZipOutputStream zos = new ZipOutputStream(bos);
String entryName = null;
entryName = fileNames[0];
for (int i = 0; i < fileNames.length; i++) {
entryName = fileNames[i];
// 創建Zip條目
ZipEntry entry = new ZipEntry(entryName);
zos.putNextEntry(entry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFiles[i]));
byte[] b = new byte[1024];
while (bis.read(b, 0, 1024) != -1) {
zos.write(b, 0, 1024);
}
bis.close();
zos.closeEntry();
}
zos.flush();
zos.close();
isSuccessful = true;
} catch (IOException e) {
}
return isSuccessful;
}
// 解析文件名
private String parse(String srcFile) {
int location = srcFile.lastIndexOf("/");
String fileName = srcFile.substring(location + 1);
return fileName;
}
}
解壓文件:
import java.util.zip.*;
import java.io.*;
public class UnzipTest {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("請輸入正確參數:java UnzipTest 需解壓的文件(e.g. d:/test.zip)");
} else {
Unzip unzip = new Unzip();
if (unzip.unzip(args[0])) {
System.out.println("文件解壓成功。");
} else {
System.out.println("文件解壓失敗。");
}
}
}
}
class Unzip {
public Unzip() {}
/*
* @param srcZipFile 需解壓的文件名
* @return 如果解壓成功返回true
*/
public boolean unzip(String srcZipFile) {
boolean isSuccessful = true;
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcZipFile));
ZipInputStream zis = new ZipInputStream(bis);
BufferedOutputStream bos = null;
//byte[] b = new byte[1024];
ZipEntry entry = null;
while ((entry=zis.getNextEntry()) != null) {
String entryName = entry.getName();
bos = new BufferedOutputStream(new FileOutputStream("d:/" + entryName));
int b = 0;
while ((b = zis.read()) != -1) {
bos.write(b);
}
bos.flush();
bos.close();
}
zis.close();
} catch (IOException e) {
isSuccessful = false;
}
return isSuccessful;
}
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!