- 相關(guān)推薦
Java的壓縮與解壓縮ZIP
壓縮是一種通過(guò)特定的算法來(lái)減小計(jì)算機(jī)文件大小的機(jī)制。這種機(jī)制是一種很方便的發(fā)明,尤其是對(duì)網(wǎng)絡(luò)用戶,因?yàn)樗梢詼p小文件的字節(jié)總數(shù),使文件能夠通過(guò)較慢的互聯(lián)網(wǎng)連接實(shí)現(xiàn)更快傳輸,此外還可以減少文件的磁盤(pán)占用空間。下面小編準(zhǔn)備了關(guān)于Java的壓縮與解壓縮ZIP,提供給大家參考!
壓縮的
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Zip {
static final int BUFFER = 2048;
public static void main(String argv[]) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream("E:\\test\\myfiles.zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
File f = new File("e:\\test\\a\\");
File files[] = f.listFiles();
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i].getName());
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
解壓縮的
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class UnZip {
static final int BUFFER = 2048;
public static void main(String argv[]) {
try {
String fileName = "E:\\test\\myfiles.zip";
String filePath = "E:\\test\\";
ZipFile zipFile = new ZipFile(fileName);
Enumeration emu = zipFile.entries();
int i=0;
while(emu.hasMoreElements()){
ZipEntry entry = (ZipEntry)emu.nextElement();
//會(huì)把目錄作為一個(gè)file讀出一次,所以只建立目錄就可以,之下的文件還會(huì)被迭代到。
if (entry.isDirectory())
{
new File(filePath + entry.getName()).mkdirs();
continue;
}
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
File file = new File(filePath + entry.getName());
//加入這個(gè)的原因是zipfile讀取文件是隨機(jī)讀取的,這就造成可能先讀取一個(gè)文件
//而這個(gè)文件所在的目錄還沒(méi)有出現(xiàn)過(guò),所以要建出目錄來(lái)。
File parent = file.getParentFile();
if(parent != null && (!parent.exists())){
parent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos,BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1)
{
bos.write(data, 0, count);
}
bos.flush();
bos.close();
bis.close();
}
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
【Java的壓縮與解壓縮ZIP】相關(guān)文章:
Java文件解壓縮示例08-21
Linux解壓縮命令詳解201609-04
PHP的壓縮函數(shù)06-21
Java與Java web的區(qū)別08-10
壓縮視頻文件的方法08-23
java習(xí)題及答案10-25
學(xué)習(xí)java技巧09-23