项目中需要用到不解压压缩包,直接读取压缩包中的文件,于是研究下了,现整理出来。
读取指定文件有两种思路,一种是在循环中遍历进行判断,另一种是直接通过文件名进行获取;
- 通过文件名直接获取
使用zipFile.getEntry(“文件名”)方法获取
public static void readZipFile1(String file,String fileName) throws Exception {
ZipFile zf = new ZipFile(file);
ZipEntry ze = zf.getEntry(fileName);
InputStream in = zf.getInputStream(ze);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer result = new StringBuffer();
while ((line = br.readLine()) != null) {
result.append(line+"\n");
}
System.out.println(result);
}
- 循环遍历中根据文件名进行判断
public static void readZipFile2(String file,String fileName) throws Exception {
ZipFile zf = new ZipFile(file);
InputStream in = new BufferedInputStream(new FileInputStream(file));
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze;
StringBuffer result = new StringBuffer();
while ((ze = zin.getNextEntry()) != null) {
if (ze.isDirectory()) {
continue;
} else {
long size = ze.getSize();
String name = ze.getName();
if (size > 0 && fileName.equals(name)) {
BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));
String line;
while ((line = br.readLine()) != null) {
result.append(line+"\n");
}
br.close();
}
}
}
System.out.println(result);
zin.closeEntry();
}
public static void readZipFile3(String file, String fileName) {
try {
ZipFile zipFile = new ZipFile(file);
StringBuffer result = new StringBuffer();
Enumeration<ZipEntry> enu = (Enumeration<ZipEntry>) zipFile.entries();
while (enu.hasMoreElements()) {
ZipEntry zipElement = (ZipEntry) enu.nextElement();
InputStream read = zipFile.getInputStream(zipElement);
String name = zipElement.getName();
if (name != null && fileName.equals(name)) {
BufferedReader br = new BufferedReader(new InputStreamReader(read));
String line;
while ((line = br.readLine()) != null) {
result.append(line+"\n");
}
br.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
- 在main方法中调用
public static void main(String[] args) throws Exception {
readZipFile("G://report.zip", "1004165931.html");
}
通过上面的几种方法可以实现直接从有压缩包中读取指定文件,当然我们也可以把指定文件写入到指定目录中再打开,实现代码如下:
/**
*
* @param file 压缩包路径
* @param saveRootDirectory 写入文件夹路径
* @param fileName 文件名
* @throws FileNotFoundException
* @throws IOException
*/
public static void writeZipFile(String file,String saveRootDirectory,String fileName) throws FileNotFoundException, IOException {
int len = 0;
ZipFile zf = new ZipFile(file);
ZipEntry ze = zf.getEntry(fileName);
InputStream read = zf.getInputStream(ze);
File writeFile = new File(saveRootDirectory + fileName);
if (!writeFile.exists()) {
File rootDirectoryFile = new File(saveRootDirectory);
//创建目录
if (!rootDirectoryFile.exists()) {
rootDirectoryFile.mkdirs();
}
//创建文件
writeFile.createNewFile();
BufferedOutputStream write = new BufferedOutputStream(new FileOutputStream(file));
//写入文件内容
while ((len = read.read()) != -1) {
write.write(len);
}
write.flush();
write.close();
}
read.close();
}
上面的代码实现了,把file
路径下的压缩包中的名为fileName
的文件写入到saveRootDirectory
目录下。