java操作壓縮包的完整代碼

==========下面是java操作壓縮包的完整代碼==========

package 壓縮包測試;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.*;
import java.util.*;
//import dianda.cwmanage.*;
//import dianda.com.util.Format;
/*
 * @author 何桂坤-2010-9-4號
 * org.apache.tools.zip.*,
 * 能夠解決不支持中文文件目錄的問題,同時,
 * Ant的獲得途徑也比較多,一般的應用服務器中有這個包
 * ,實在不行去下載個tomcat5.X,裏面也有ant.jar,本人經過測試,可以使用。
 */
public class CompressBook {
 
public CompressBook() {
}
String name="";
public void zip(String inputFileName) throws Exception {//傳入文件名
 File filename=new File(inputFileName);//實例化文件
 name=filename.getName();//得到完整文件名
 String newnameString=filename.getName().substring(0,filename.getName().indexOf('.'));//截取有用的文件名
 String zipFileName="f://IO流測試/"+newnameString+".zip";//設置打包後文件名字
 System.out.println("將被打包的文件:"+zipFileName);//輸出要打包的文件名
 zip(zipFileName, filename);//參數1 參數2根據名子實例化一個文件
}

private void zip(String zipFileName, File inputFile) throws Exception {
// ZipOutputStream以 ZIP 文件格式寫入文件實現輸出流過濾器。包括對已壓縮和未壓縮條目的支持。
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
//參數1{ZipOutputStream流}  參數2{被打包的文件File} 參數3 {壓縮包裏面被打包的文件的新名}
File file=new File(zipFileName);
String newnameString=file.getName().substring(0,file.getName().indexOf('.'));//截取有用的文件名
System.out.println(newnameString);
zip(out, inputFile, name);
out.close();//關閉流
}

private void zip(ZipOutputStream out, File f, String base) throws Exception {
 if (f.isDirectory())// 測試此抽象路徑名錶示的文件是否是一個目錄
 {
  File[] fl = f.listFiles();
   out.putNextEntry(new ZipEntry(base + "/"));
 }
 else {
       out.putNextEntry(new ZipEntry(base));
    FileInputStream in = new FileInputStream(f);
    int b;
    System.out.println("===打包以後裏面的文件名===:"+base);
      while ( (b = in.read()) != -1) {
     out.write(b);//把裏面的內容讀出來從新寫入新文件
  }
  in.close();
    }
}
public static void main(String[] args) {
 CompressBook compressBook=new CompressBook();
 try {
  compressBook.zip("f://IO流測試/2010-09-04生日小寫.txt");
  compressBook.zip("f://IO流測試/IO.html");
 } catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
  /*唯一遺憾,美中不足的是,無論,
  * java.util.zip或者org.apache.tools.zip
  * 都不能解壓rar工具打成的rar包,
  * 搜了半天也找不到採用java解壓rar工具打成的包,
  * 盼望哪位高人能夠提供解壓rar工具打成的包,
  */
          //代碼來自heguikun個人網站
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章