Java实现Zip压缩目录中的所有文件

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class FolderZip {
private static String sourcepath="C:\\temp";
private static List<String>folderList=new ArrayList<String>(Arrays.asList(sourcepath));
private static List<String>folderList2=new ArrayList<String>(Arrays.asList("D:\\tmp"+File.separator+sourcepath.substring(sourcepath.lastIndexOf(File.separator))));
private static FileInputStream fis = null;
private static FileOutputStream fos = null;
private static ZipOutputStream zipOut = null;
    public static void main(String[] args) {
        for (int j = 0; j < folderList.size(); j++) {
            new File(folderList2.get(j)).mkdirs();
            String[] file = new File(folderList.get(j)).list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (folderList.get(j).endsWith(File.separator))
                    temp = new File(folderList.get(j), file[i]);
                else
                    temp = new File(folderList.get(j), file[i]);
                File zipFile = new File(folderList2.get(j), temp.getName()
                        + ".zip");
                if (temp.isFile() && !zipFile.exists())
                    try {
                        fis = new FileInputStream(temp);
                        fos = new FileOutputStream(zipFile);
                        zipOut = new ZipOutputStream(fos);
                        ZipEntry entry = new ZipEntry(temp.getName());
                        zipOut.putNextEntry(entry);
                        int nNumber;
                        byte[] buffer = new byte[20480];
                        while ((nNumber = fis.read(buffer)) != -1)
                            zipOut.write(buffer, 0, nNumber);
                        zipOut.flush();
                    } catch (IOException e) {
                        continue;
                    } finally {
                        try {
                            zipOut.close();
                            fos.close();
                            fis.close();
                        } catch (IOException e) {
                        }
                    }
                else if (temp.isDirectory()) {
                    folderList
                            .add(folderList.get(j) + File.separator + file[i]);
                    folderList2.add(folderList2.get(j) + File.separator
                            + file[i]);
                }
            }
        }
    }
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:android连接服务器下载文件工具类

下一篇:android安装应用程序工具类