您的位置:首页 > 编程语言 > Java开发

Java使用Zip包压缩文件示例

2012-10-12 11:27 801 查看

Java使用Zip包压缩文件示例

public static void zip() throws FileNotFoundException, IOException {

File root = new File("svn-1.6");
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(root.getPath()+".zip"));

zipDirectory(root,zipOutputStream);

zipOutputStream.close();
}

private static void zipDirectory(File root,ZipOutputStream zipOutputStream) throws IOException{

String zipPath = "";
zipDirectory(zipPath,root,zipOutputStream);
}

private static void zipDirectory(String basePath,File root,ZipOutputStream zipOutputStream) throws IOException{

if(basePath.length()>0){
basePath += "/";
}
File[] files = root.listFiles();
for (int i = 0; i < files.length; i++) {

File file = files[i];
if(file.isFile()){
System.out.println(file.getPath());
ZipEntry zipEntry = new ZipEntry(basePath + file.getName());
zipOutputStream.putNextEntry(zipEntry);

FileInputStream inputStream = new FileInputStream(file);
int count;byte[] buffer = new byte[1024];

while((count = inputStream.read(buffer, 0, buffer.length))>0){

zipOutputStream.write(buffer, 0, count);
}
inputStream.close();
}else if(file.isDirectory()){
ZipEntry zipEntry = new ZipEntry(basePath + file.getName()+"/");

zipOutputStream.putNextEntry(zipEntry);
zipDirectory(basePath + file.getName(),file,zipOutputStream);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: