当前位置:编程学习 > JAVA >>

一个撇脚的java压缩文件工具类

今天弄里一个压缩文件的工具类,功能不是很完善,只支持压缩后单级目录,二级文件夹的文件名好像只能用中文,并且解压后还是乱码。请各位高手大侠批评指教,不胜感激!
package tests; 
 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipOutputStream; 
 
public class ZipUtil { 
    private static File zip; 
    private static ZipOutputStream zipOut; 
    private InputStream input; 
    public ZipUtil(){ 
        try { 
            zipOut = new ZipOutputStream(new FileOutputStream(zip)); 
            zipOut.setComment("hello2"); 
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        } 
    } 
    public void zipFile(File file) { 
        if (file.isDirectory()) { 
            File[] files = file.listFiles(); 
            for (int i = 0; i < files.length; i++) { 
                if (files[i].isDirectory()) { 
                    zipFile(files[i]); 
                } else { 
                    try { 
                        input = new FileInputStream(files[i]); 
                        zipOut.putNextEntry(new ZipEntry(file.getName() 
                                + File.separator + files[i].getName())); 
                        int temp = 0; 
                        while ((temp = input.read()) != -1) { 
                            zipOut.write(temp); 
                        } 
                        input.close(); 
                    } catch (FileNotFoundException e) { 
                        e.printStackTrace(); 
                    } catch (IOException e) { 
                        e.printStackTrace(); 
                    } 
                } 
            } 
            try { 
                zipOut.close(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } else { 
            try { 
                input = new FileInputStream(file); 
                zipOut.putNextEntry(new ZipEntry(file.getName())); 
                int temp = 0; 
                while ((temp = input.read()) != -1) { 
                    zipOut.write(temp); 
                } 
                input.close(); 
                zipOut.close(); 
            } catch (FileNotFoundException e) { 
                e.printStackTrace(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
    public static void main(String[] args) { 
        zip = new File("d:" + File.separator + "hello.rar"); 
        File file = new File("d:" + File.separator + "hello"); 
        new ZipUtil().zipFile(file); 
    } 
}

作者“AI,MYY!”

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,