Java使用Zip包压缩文件示例
来源:互联网 发布:图片横向滚动js代码 编辑:程序博客网 时间:2024/06/05 05:40
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);
- }
- }
- }