如何复制某些目录中的所有文件并使用java重新创建目录结构?

时间:2015-07-13 19:18:57

标签: java file directory

而不是一次复制一个文件。我正在压缩所有文件并解压缩它们。我使用下面的代码来压缩和解压缩文件,但是如何解压缩它们并通过文件描述动态地重新创建目录结构。 例如:如果文件是

c://users//desktop//635289512-251.txt

我需要将文件放在

c://users//desktop//635_users//2895_access//635289512-251.txt

谢谢你的帮助。

public static void zip(File directory, File zipfile) throws IOException {
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<File>();
    queue.push(directory);
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = out;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.pop();
            for (File kid : directory.listFiles()) {
                String name = base.relativize(kid.toURI()).getPath();
                if (kid.isDirectory()) {
                    queue.push(kid);
                    name = name.endsWith("/") ? name : name + "/";
                    zout.putNextEntry(new ZipEntry(name));
                } else {
                    zout.putNextEntry(new ZipEntry(name));
                    copy(kid, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        res.close();
    }
}

 public static void unzip(File zipfile, File directory) throws IOException {
    ZipFile zfile = new ZipFile(zipfile);
    Enumeration<? extends ZipEntry> entries = zfile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File file = new File(directory, entry.getName());
        if (entry.isDirectory()) {
            file.mkdirs();
        } else {
            file.getParentFile().mkdirs();
            InputStream in = zfile.getInputStream(entry);
            try {
                copy(in, file);
            } finally {
                in.close();
            }
        }
    }
}

0 个答案:

没有答案