java压缩文件,目录

摘要: package common;import java.io.*;import org.apache.tools.zip.*;

package common;

import java.io.*;
import org.apache.tools.zip.*;


public class Zip
{
private static void zipDirectory(ZipOutputStream zos, String dirName,
String basePath) throws Exception
{
File dir = new File(dirName);
if (dir.exists())
{
File files[] = dir.listFiles();

if (files.length > 0)
{
for (File file : files)
{

if (file.isDirectory())
{
zipDirectory(zos, file.getPath(), basePath
+ file.getName().substring(
file.getName().lastIndexOf(
File.separator) + 1)
+ File.separator);
}
else
zipFile(zos, file.getPath(), basePath);
}
}
else
{
ZipEntry ze = new ZipEntry(basePath);
zos.putNextEntry(ze);
}
}
}

private static void zipFile(ZipOutputStream zos, String filename,
String basePath) throws Exception
{
File file = new File(filename);

if (file.exists())
{

FileInputStream fis = new FileInputStream(filename);
ZipEntry ze = new ZipEntry(basePath + file.getName());

zos.putNextEntry(ze);
byte[] buffer = new byte[8192];
int count = 0;
while ((count = fis.read(buffer)) > 0)
{
zos.write(buffer, 0, count);
}
fis.close();
}
}

public static void compress(String zipFilename, String... paths)
throws Exception
{
compress(new FileOutputStream(zipFilename), paths);

}

public static void compress(OutputStream os, String... paths)
throws Exception
{
ZipOutputStream zos = new ZipOutputStream(os);

for (String path : paths)
{
if(path.equals("")) continue;
java.io.File file = new java.io.File(path);
if (file.exists())
{

if (file.isDirectory())
{
zipDirectory(zos, file.getPath(), file.getName() + File.separator);
}
else
{
zipFile(zos, file.getPath(), "");
}
}
}
zos.close();
}
}

上一篇: java MD5,DES加密,解密
下一篇: java 生成图片验证码
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号