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:的根目录中创建一个名为 test.zip的 zip,它将包含一个名为 mytext.txt的文件。当然,您可以添加更多的 zip 条目,也可以像下面这样指定一个子目录:
ZipEntry e = new ZipEntry("folderName/mytext.txt");
要编写 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();
Map<String, String> env = new HashMap<>();
// Create the zip file if it doesn't exist
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);
}