工具類之文件與壓縮解壓縮

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class FileZip {

    /**
     * @param inputFileName 你要壓縮的文件夾(整個完整路徑)
     * @param zipFileName 壓縮後的文件(整個完整路徑)
     */
    public static void zip(String inputFileName, String zipFileName) throws Exception {
        zip(zipFileName, new File(inputFileName));
    }

    private static void zip(String zipFileName, File inputFile) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                zipFileName));
        if(inputFile.isDirectory())
        zip(out, inputFile, "");
        else
        zip(out, inputFile, inputFile.getName());
        out.flush();
        out.close();
    }

    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[i].getName());
            }
        } else {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            int b; 
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
        }
        System.out.println("壓縮完畢");
    }
    
     public static void main(String [] temp){       
         try {           
            zip("D:\\web\\photo\\ueditor\\jsp\\upload\\image\\20160705\\abc.doc","D:\\web\\photo\\ueditor\\jsp\\upload\\image\\20160705\\abc.zip");//你要壓縮的文件夾      和  壓縮後的文件 
            //  zip("D:\\web\\photo\\ueditor\\jsp\\upload\\image\\20160705","D:\\web\\photo\\ueditor\\jsp\\upload\\image\\20160705.zip");    
         }catch (Exception ex) {       
                 ex.printStackTrace();    
             }   
        }
}



//=====================文件壓縮=========================
/*//把文件壓縮成zip
File zipFile = new File("E:/demo.zip");
//定義輸入文件流
InputStream input = new FileInputStream(file);
//定義壓縮輸出流    
ZipOutputStream zipOut = null;
//實例化壓縮輸出流,並制定壓縮文件的輸出路徑  就是E盤下,名字叫 demo.zip
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
//設置註釋
zipOut.setComment("www.demo.com");
int temp = 0;
while((temp = input.read()) != -1) {
    zipOut.write(temp);    
}        
input.close();
zipOut.close();*/
//==============================================
相關文章
相關標籤/搜索