用java壓縮文件

 

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 Eddy {
  public static void main(String[] args)
     {
   try{
       File f = new File("C:/onlinelog.txt"); 
       FileInputStream fis = new FileInputStream(f);
       BufferedInputStream bis = new BufferedInputStream(fis);  //緩衝輸入流(BufferedInputStream)
       byte[] buf = new byte[1024];
       int len;  //set len variable
       FileOutputStream fos = new FileOutputStream(f.getName()+".zip");
       BufferedOutputStream bos = new BufferedOutputStream(fos);
       ZipOutputStream zos = new ZipOutputStream(bos);//壓縮包   //zip輸出流(stream)
       ZipEntry ze = new ZipEntry(f.getName());//這是壓縮包名裏的文件名//zipEntry類
     
       ze.setTime(System.currentTimeMillis());
       System.out.println(ze.toString());
       System.out.println(ze.getName());
       System.out.println(ze.clone());  //clone
       zos.putNextEntry(ze);//寫入新的 ZIP 文件條目並將流定位到條目數據的開始處
      
     
       while((len=bis.read(buf))!=-1)  //當!=-1 不等於-1時。也就是有數據。執行以下語句塊
       {
          zos.write(buf,0,len); //第一個參數 byte數組buf,第二個offset,第三個len
          zos.flush();
          System.out.println(ze.getSize());  //得到onlinelog大小,未知返回-1
       }
       try{
       bis.close();
       zos.close();
       }
       catch(Exception e){
          e.printStackTrace();
          System.err.println("bis.close() zos.close() error");
       }
     }
    
 catch(Exception ex){
  ex.printStackTrace();
  System.err.println("error");
  
 }
 
}
}

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