侧边栏壁纸
博主头像
丛庆

没事儿写代码,有事写代码。email:1024@cong.zone

  • 累计撰写 116 篇文章
  • 累计创建 97 个标签
  • 累计收到 4 条评论

【java】【java工具类】使用java 获取zip 7z rar rar5 等压缩文件中的文件名集合

丛庆
2021-09-05 / 0 评论 / 0 点赞 / 907 阅读 / 1,638 字 / 正在检测是否收录...
温馨提示:
部分资料和图片来源于网络,如有危害到您的利益请与我联系删除,1024@cong.zone。

需求目标

使用java 获取指定压缩文件中的文件名集合

依赖

        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>java-unrar</artifactId>
            <version>1.7.0-8</version>
        </dependency>
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding</artifactId>
            <version>16.02-2.01</version>
        </dependency>
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding-all-platforms</artifactId>
            <version>16.02-2.01</version>
        </dependency>

代码

    /**
     * 获取压缩文件中的文件名称(不包括文件夹名称)
     * @param filePath 文件路径
     * @param isIncludeSuffix 是否包含后缀名 true包含 false不包含
     * @return 文件名的集合
     * @throws Exception
     */
    public static List<String> getCompressFileContentFileName(String filePath, boolean isIncludeSuffix) throws Exception {
        List<String> list = new ArrayList<>();
        RandomAccessFile randomAccessFile = null;
        IInArchive inArchive = null;
        randomAccessFile = new RandomAccessFile(filePath, "r");
        inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
        for (int i = 0; i < inArchive.getNumberOfItems(); i++) {
            String fileFath = inArchive.getStringProperty(i, PropID.PATH);
            String b = inArchive.getStringProperty(i, PropID.IS_FOLDER);
            if ("-".equals(b)) {
                String fileName = new File(fileFath).getName();
                // true包含后缀 false不包含后缀
                list.add(isIncludeSuffix ? fileName : removeSuffix(fileName));
            }
        }
        return list;
    }

    /**
     * 去除文件名的后缀
     * @param fileName
     * @return
     */
    private static String removeSuffix(String fileName){
        // 不包含后缀名
        int i = fileName.lastIndexOf(".");
        if (i == -1){
            return fileName;
        }
        String fileNameNoSuffixName = fileName.substring(0, i);
        return fileNameNoSuffixName;
    }
0
博主关闭了当前页面的评论