java zip 创建目录_java.util.zip-重新创建目录结构

的URI类是具有相对路径的工作是有用的。

File mydir = new File("C:\\mydir");

File myfile = new File("C:\\mydir\\path\\myfile.txt");

System.out.println(mydir.toURI().relativize(myfile.toURI()).getPath());

上面的代码将发出字符串path/myfile.txt。

为了完整起见,以下是zip用于归档目录的方法:

public static void zip(File directory, File zipfile) throws IOException {

URI base = directory.toURI();

Deque queue = new LinkedList();

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();

}

}

这段代码不会保留日期,我不确定它会对符号链接之类的东西有什么反应。没有尝试添加目录条目,因此不会包含空目录。

相应的unzip命令:

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();

}

}

}

}

它们依赖的实用方法:

private static void copy(InputStream in, OutputStream out) throws IOException {

byte[] buffer = new byte[1024];

while (true) {

int readCount = in.read(buffer);

if (readCount < 0) {

break;

}

out.write(buffer, 0, readCount);

}

}

private static void copy(File file, OutputStream out) throws IOException {

InputStream in = new FileInputStream(file);

try {

copy(in, out);

} finally {

in.close();

}

}

private static void copy(InputStream in, File file) throws IOException {

OutputStream out = new FileOutputStream(file);

try {

copy(in, out);

} finally {

out.close();

}

}

缓冲区大小完全是任意的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值