1 /** 2 * 作者认为解压缩最安全的方法 3 * 先创建所有的文件夹 4 * 之后创建再文件 5 * <p> 6 * 原因:未处理好当压缩文件夹下第一个是一个文件夹,考虑到存在有文件可以没有(.)等这些标识符,无法识别出是否是文件夹还是文件, 7 * 故根据zipEntry.getName后续返回值是否存在后续文件夹即(\\符号)判断是否其是文件夹,进而可以创建出压缩包下所有的文件夹 8 * 当所有的文件夹创建好之后,压缩文件与现有的文件目录的唯一区别就是文件 9 * 此时,可以直接对压缩文件目录与现解压文件目录进行比较,如果不存在则进行copy,如果存在,则不处理 10 * 如果有发现更好的处理方式,将继续更改 11 */ 12public class ZipFileDemo { 13 public static void main(String[] args) { 14 createFolder("E:\\HUAT2.zip","E:\\aaa"); 15 } 16 17 public static void createFolder(String filePath, String savePath) { 18 ZipInputStream inputStream = null; 19 ZipEntry zipEntry = null; 20 try { 21 inputStream = new ZipInputStream(new FileInputStream(filePath)); 22 while ((zipEntry = inputStream.getNextEntry()) != null) { 23 String fileName = zipEntry.getName(); 24 File file = new File(savePath + File.separator + fileName); 25 if (!file.getParentFile().exists()) { 26 file.getParentFile().mkdirs(); 27 } 28 } 29 createFile(filePath, savePath); 30 } catch (FileNotFoundException e) { 31 e.printStackTrace(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } finally { 35 try { 36 inputStream.close(); 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } 40 } 41 } 42 43 private static void createFile(String filePath, String savePath) { 44 ZipInputStream inputStream = null; 45 ZipEntry zipEntry = null; 46 OutputStream outputStream = null; 47 try { 48 inputStream = new ZipInputStream(new FileInputStream(filePath)); 49 while ((zipEntry = inputStream.getNextEntry()) != null) { 50 String fileName = zipEntry.getName(); 51 System.out.println(fileName); 52 File file = new File(savePath + File.separator + fileName); 53 54 if (!file.exists()) { 55 outputStream = new FileOutputStream(file, true); 56 int len = 0; 57 byte[] bytes = new byte[1024]; 58 while ((len = inputStream.read(bytes)) != -1) { 59 outputStream.write(bytes, 0, len); 60 } 61 outputStream.close(); 62 } 63 } 64 inputStream.close(); 65 } catch (FileNotFoundException e) { 66 e.printStackTrace(); 67 } catch (IOException e) { 68 e.printStackTrace(); 69 } 70 71 } 72} 73
Java的文件解压-Zip格式

红烧土豆泥
2021-07-15
2106 0 0
点赞
收藏
评论区
加载中...