KKFileView(三)

2021SC@SDUSC

目录

 一、 读取zip文件 

1.用到的数据结构

2.具体流程

 二 、 7Z,rar,zip压缩文件的区别


 一、 读取zip文件 

1.用到的数据结构

FileNode:将每一个文件定义为一个结点,包括:

String originName:文件名称,
 String fileName:结点名称,,如果该结点时目录,保存为level+文件名称,否则为压缩包名称+文件名称
 String parentFileName:父文件名称, 
List<FileNode> childList:子结点列表,
 boolean directory:是否为目录

appender:哈希表,保存文件结点

Map<String, FileNode>

2.具体流程

  • 通过zipFile读取,运用zipFile类中自带的getEntries()方法,得到枚举即所有的文件条目entries
    ZipFile zipFile = new ZipFile(filePath, KkFileUtils.getFileEncode(filePath));
                Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

  • 将得到的文件条目按照名称长度排序
    sortedEntries.sort(Comparator.comparingInt(o -> o.getName().length()));
  •  判断是否为目录,不是目录则开启加入待解压文件的list列表
if (!directory) {
                    childName = archiveFileName + "_" + originName;
                    System.out.println("childname1:"+childName);
                    entriesToBeExtracted.add(Collections.singletonMap(childName, entry));
                }
  •  将该文件对应的结点加入其父文件结点的子结点列表中,如果不存在父文件结点,则将其定为根结点
    addNodes(appender, parentName, node)//加入父结点对于的子结点列表
    
    if (appender.containsKey(parentName)) {
                appender.get(parentName).getChildList().add(node);
                appender.get(parentName).getChildList().sort(sortComparator);//排序
            } else {
                // 根节点
                FileNode nodeRoot = new FileNode(parentName, parentName, "", new ArrayList<>(), true);
                nodeRoot.getChildList().add(node);
                appender.put("", nodeRoot);
                appender.put(parentName, nodeRoot);
            }

  •  将该文件加入哈希表中
    appender.put(childName, node)

 二 、 7Z,rar,zip压缩文件的区别

7z压缩率最高,RAR安全性高,ZIP使用范围广

详细介绍zip、rar、7z的不同以及优势

1.zip文件解压

private void extractZipFile(String childName, InputStream zipFile) {
            String outPath = fileDir + childName;
            try (OutputStream ot = new FileOutputStream(outPath)) {
                byte[] inByte = new byte[1024];
                int len;
                while ((-1 != (len = zipFile.read(inByte)))) {
                    ot.write(inByte, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

2. 7Z文件解压

 FileOutputStream out = new FileOutputStream(fileDir + childName);
                    byte[] content = new byte[(int) entry.getSize()];
                    sevenZFile.read(content, 0, content.length);
                    out.write(content);
                    out.close();
                    entry = sevenZFile.getNextEntry();

3.Rar文件解压

 String outPath = fileDir + childName;
            try (OutputStream ot = new FileOutputStream(outPath)) {
                archive.extractFile(header, ot);
            } catch (IOException | RarException e) {
                e.printStackTrace();
            }

猜你喜欢

转载自blog.csdn.net/eldrida1/article/details/120719914