- /*
- *這個類用來壓縮和解壓
- *
- * */
- package server;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.util.Enumeration;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipFile;
- import java.util.zip.ZipOutputStream;
- public class Zip {
- public static int BUFFER;
- public Zip()
- {
- BUFFER = 2048;
- }
- public void Yasuo(String test,String ff)
- {
- try {
- BufferedInputStream origin = null;
- // FileOutputStream dest = new FileOutputStream("E://test//myfiles.zip");
- FileOutputStream dest = new FileOutputStream(test);
- ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream (dest));
- byte data[] = new byte[BUFFER];
- // File f = new File("e://test//a//");
- File f = new File(ff);
- 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();
- }
- }
- public void Jieya(String name,String path)
- {
- try {
- // String fileName = "E://test//myfiles.zip";
- // String filePath = "E://test//";
- String fileName=name;
- String filePath=path;
- ZipFile zipFile = new ZipFile(fileName);
- Enumeration emu = zipFile.entries();
- int i=0;
- while(emu.hasMoreElements()){
- ZipEntry entry = (ZipEntry)emu.nextElement();
- //會把目錄作爲一個file讀出一次,所以只建立目錄就可以,之下的文件還會被迭代到。
- if (entry.isDirectory())
- {
- new File(filePath + entry.getName()).mkdirs();
- continue;
- }
- BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
- File file = new File(filePath + entry.getName());
- //加入這個的原因是zipfile讀取文件是隨機讀取的,這就造成可能先讀取一個文件
- //而這個文件所在的目錄還沒有出現過,所以要建出目錄來。
- 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();
- }
- }
- }
zip.java
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.