需求目标
使用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;
}