Java 打包zip压缩文件,和读取不解压的zip文件

分享 未结 精帖 0 126
绝尘
绝尘 2018-06-15

Java打包压缩包,简单代码如下:


//文件压缩到zip
@Test
public void createZip() throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File("hello.zip")));
BufferedOutputStream bos = new BufferedOutputStream(zos);

List<String> files = asList("log.txt");//文件列表

for (String fileName : files) {
File file = new File(fileName);
ZipEntry zipEntry = new ZipEntry("file/" + file.getName());
zos.putNextEntry(zipEntry);//设置即将用来写的文件

FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);

int read;
while ((read = bis.read()) != -1){
bos.write(read);
bos.flush();
}
}
zos.close();
}


Java读取压缩包,不解压zip直接读取文件内容:  

//读取压缩包
@Test
public void readZip() throws IOException {
ZipFile zipFile = new ZipFile(new File("hello.zip"));
Enumeration<? extends ZipEntry> entries = zipFile.entries();

while (entries.hasMoreElements()){
ZipEntry zipEntry = entries.nextElement();
InputStream is = zipFile.getInputStream(zipEntry);

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

String str;
while ((str = reader.readLine()) != null){
System.out.println(str);
}
}
}


可拷贝到自己代码中,main方法中运行,看看效果,
更多个性化使用,自行定制,

源码可到  我的gitee 账号下 demo---> jdk-demo---> zip 查看


个人博客地址:http://1216.top 码云/GitHub:https://gitee.com/tc608
还有不明白?追问
  • 消灭零回复