/**
 * 作者认为解压缩最安全的方法
 * 先创建所有的文件夹
 * 之后创建再文件
 * <p>
 * 原因:未处理好当压缩文件夹下第一个是一个文件夹,考虑到存在有文件可以没有(.)等这些标识符,无法识别出是否是文件夹还是文件,
 * 故根据zipEntry.getName后续返回值是否存在后续文件夹即(\\符号)判断是否其是文件夹,进而可以创建出压缩包下所有的文件夹
 * 当所有的文件夹创建好之后,压缩文件与现有的文件目录的唯一区别就是文件
 * 此时,可以直接对压缩文件目录与现解压文件目录进行比较,如果不存在则进行copy,如果存在,则不处理
 * 如果有发现更好的处理方式,将继续更改
 */
public class ZipFileDemo {
    public static void main(String[] args) {
        createFolder("E:\\HUAT2.zip","E:\\aaa");
    }
    public static void createFolder(String filePath, String savePath) {
        ZipInputStream inputStream = null;
        ZipEntry zipEntry = null;
        try {
            inputStream = new ZipInputStream(new FileInputStream(filePath));
            while ((zipEntry = inputStream.getNextEntry()) != null) {
                String fileName = zipEntry.getName();
                File file = new File(savePath + File.separator + fileName);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
            }
            createFile(filePath, savePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private static void createFile(String filePath, String savePath) {
        ZipInputStream inputStream = null;
        ZipEntry zipEntry = null;
        OutputStream outputStream = null;
        try {
            inputStream = new ZipInputStream(new FileInputStream(filePath));
            while ((zipEntry = inputStream.getNextEntry()) != null) {
                String fileName = zipEntry.getName();
                System.out.println(fileName);
                File file = new File(savePath + File.separator + fileName);
                if (!file.exists()) {
                    outputStream = new FileOutputStream(file, true);
                    int len = 0;
                    byte[] bytes = new byte[1024];
                    while ((len = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                    }
                    outputStream.close();
                }
            }
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Java的文件解压-Zip格式
点赞
收藏

 
  
  
  
  
 
 
 
