今天,接到个任务,要求实现一个从压缩包中读取文件
我就简单找了下,使用Java自带的工具类中的
/**
* 读取一个zip文件的内容,内容限定于字符文件
* @param srcPath
*/
public static void readFromZip(String srcPath) {
ZipEntry zipEntry = null;
ZipInputStream zipInputStream = null;
InputStream in = null;
try {
ZipFile zipFile = new ZipFile(srcPath);
in = new BufferedInputStream(new FileInputStream(srcPath));
zipInputStream = new ZipInputStream(in);
while ( ( zipEntry = zipInputStream.getNextEntry() ) != null) {
if( !zipEntry.isDirectory() ) {
//这里得到压缩包中的一个文件
BufferedReader reader = null;
if ( zipEntry.getSize() > 0 ) {
reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
String line = null;
while ( ( line = reader.readLine() ) != null ) {
System.out.println(line);
//TODO 得到每一数据,进行处理
}
reader.close();
}
}
}
zipInputStream.closeEntry();
} catch (IOException e) {
System.out.println("这里抛出异常1121");
e.printStackTrace();
}
}
不过又需要对已经加密的压缩文件进行处理,加密的文件进行处理,在网上找到Zip4j开源项目
/**
* 读取一个带密码的压缩文件的文件内容
* @param zipFile 压缩文件
* @param password 密码
* @throws ZipException
*/
public static void readFromZipWithPassword(String zipFile, String password) throws ZipException {
long startTime = System.currentTimeMillis();
ZipFile zipFile2 = new ZipFile(zipFile);
//设置编码格式
zipFile2.setFileNameCharset("GBK");
if (!zipFile2.isValidZipFile()) {
throw new ZipException("文件不合法或不存在");
}
//检查是否需要密码
if (zipFile2.isEncrypted()) {
zipFile2.setPassword(password);
}
List<FileHeader> fileHeaderList = zipFile2.getFileHeaders();
for (int i = 0; i < fileHeaderList.size(); i++) {
FileHeader fileHeader = fileHeaderList.get(i);
BufferedReader reader = new BufferedReader(new InputStreamReader(zipFile2.getInputStream(fileHeader)));
String line;
try {
while ( ( line = reader.readLine() ) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("解压成功!");
long endTime = System.currentTimeMillis();
System.out.println("耗时:" + (endTime - startTime) + "ms");
}