如何在java中创建多层文件_如何在Java中创建zip文件

问题

我有一个动态文本文件,根据用户的查询从数据库中选择内容。我必须将此内容写入文本文件并将其压缩到servlet中的文件夹中。我该怎么做?

#1 热门回答(161 赞)

看看这个例子:

StringBuilder sb = new StringBuilder();

sb.append("Test String");

File f = new File("d:\\test.zip");

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));

ZipEntry e = new ZipEntry("mytext.txt");

out.putNextEntry(e);

byte[] data = sb.toString().getBytes();

out.write(data, 0, data.length);

out.closeEntry();

out.close();

这将创建一个位于D的根目录中的Zip文件:名为"test.zip",它将包含一个名为"mytext.txt"的文件。当然,你可以添加更多zip条目,还可以指定子目录,如:

ZipEntry e = new ZipEntry("folderName/mytext.txt");

#2 热门回答(83 赞)

Java 7内置了ZipFileSystem,可用于从zip文件创建,写入和读取文件。

Java Doc: ZipFileSystem Provider

Map env = new HashMap<>();

env.put("create", "true");

URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");

try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {

Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");

Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");

// copy a file into the zip file

Files.copy(externalTxtFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);

}

#3 热门回答(27 赞)

要编写ZIP文件,请使用ZipOutputStream。对于要放入ZIP文件的每个条目,可以创建ZipEntry对象。你将文件名传递给ZipEntry构造函数;它设置其他参数,如文件日期和解压缩方法。你可以根据需要覆盖这些设置。然后,调用ZipOutputStream的putNextEntry方法开始编写新文件。将文件数据发送到ZIP流。完成后,调用closeEntry。对要存储的所有文件重复此操作。这是一个代码框架:

FileOutputStream fout = new FileOutputStream("test.zip");

ZipOutputStream zout = new ZipOutputStream(fout);

for all files

{

ZipEntry ze = new ZipEntry(filename);

zout.putNextEntry(ze);

send data to zout;

zout.closeEntry();

}

zout.close();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值