目录
一、简介
很多时候我们需要使用java读取zip的内容,读取zip中的txt(其他文件类似),本文使用java编写了简单的读取zip中txt内容的代码。可以支持GBK或者UTF8编码格式的zip文件,支持zip中的txt文件内容编码格式内容为GBK或者UTF8格式,原生java读取不需要依赖三方包。
二、代码
由于没啥太多好描述的,废话不多说,直接上代码:
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
/**
* java读取zip中的txt内容
* @author kevin
* @date 2021/2/26
*/
public class ReadZipFile {
public static void main(String[] args){
String path = "C:\\Users\\64998\\Desktop\\数据库脚本.zip";
readTxtInZip(path);
}
public static void readTxtInZip(String path){
ZipFile zFile = null;
ZipInputStream zIn = null;
try{
zFile = new ZipFile(path, Charset.forName("GBK"));
zIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(path)),
Charset.forName("GBK"));
try {
zFile.getInputStream(zIn.getNextEntry());
}catch (Exception e){
zFile = new ZipFile(path, StandardCharsets.UTF_8);
zIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(path)),
StandardCharsets.UTF_8);
}
ZipEntry zEntry;
while ((zEntry = zIn.getNextEntry()) != null) {
if (zEntry.getName().endsWith(".txt")) {
BufferedReader bfr = new BufferedReader(new InputStreamReader(zFile.getInputStream(zEntry)));
String testLine = bfr.readLine();
if (!Charset.forName("GBK").newEncoder().canEncode(testLine)) {
bfr.close();
bfr = new BufferedReader(new InputStreamReader(zFile.getInputStream(zEntry),
Charset.forName("GBK")));
}
String line;
while ((line = bfr.readLine()) != null) {
System.out.println(line);
}
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (zFile != null) {
zFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (zIn != null) {
zIn.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}