目录
- zip压缩
- ZipInputStream读取
- ZipOutputStream写入
zip压缩
zip文档可以以压缩格式存储一个或多个文件,可以使用ZipInputStream读取Zip文档,使用ZipOutputStream来写入到Zip文件中
ZipInputStream读取
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze;
// getNextEntry返回描述这个项的ZipEntry的对象
while ((ze = zin.getNextEntry()) != null) {
// getInputStream获取用于读取该项的输入流
BufferedReader br = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze), charset));
// 业务逻辑 todo
br.close();
// closeEntry关闭当前打开的项
zin.closeEntry();
}
zin.close();
ZipOutputStream写入
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
File fileWillZip = 编程客栈new File(dir);
if (fileWillZip.exists()) {
// 需要压缩的文件是文件夹。需要递归进行压缩
if(fileWillZip.isDirectory()){
compressZip(zipOut,fileWillZip,fileWillZip.getName());
} else { // 是文件,直接压缩
zip(zipOut,fileWillZip,dir);
}
}
zipOut.closeEntry();
zipOut.close();
private void compressZip(ZipOutputStream zipOutput, Fjsile file, String suffixpath) {
File[] listFiles = file.listFiles();// 列出所有的文件
for(File fi : listFiles){
if(fi.isDirectory()){ // 如果是文件夹,继续递归
if(suffixpath.equals("")){
compressZip(zipOutput, fi, fi.getName());
}else{
compressZip(zipOutput, fi, suffixpath + File.separator + fi.getName());
}
}else{
zip(zipOutput, fi, su编程客栈ffixpath);
}
}
}
public void zip(ZipOutputStream zipOutput, File file, String suffixpath) {
try {
// 创建ZipEntry对象
ZipEntry zEntry = null;
if(suffixpath.equals("")){
zEntry = new ZipEntry(file.getName());
}else{
zEntry = new ZipEntry(suffixpath + Fipythonle.separator + file.getName());
}
// putNextEntry将给定的ZipEntry中的信息写出到输出流,并定位用于写出数据的流,然后这些数据可以通过write方法写出到这个输出流中
编程客栈 zipOutput.putNextEntry(zEntry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
int read = 0;
while((read = bis.read(buffer)) != -1){
zipOutput.write(buffer, 0, read);
}
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
以上就是Java如何使用zip压缩实现读取写入的详细内容,更多关于java zip压缩读取写入的资料请关注编程客栈(www.devze.com)其它相关文章!
加载中,请稍侯......
精彩评论