如何在Java中创建zip文件

Ash*_*wal 136 java zip

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

Chr*_*ris 210

看看这个例子:

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();
Run Code Online (Sandbox Code Playgroud)

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

ZipEntry e = new ZipEntry("folderName/mytext.txt");
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到有关使用java压缩的更多信息:

http://www.oracle.com/technetwork/articles/java/compress-1565076.html

  • @RobA你没有遗漏任何东西.StringBuilder确实意味着包含OP从他的数据库中获得的文本.OP只需替换getTextFromDatabase()之类的"测试字符串"(包括引号) (3认同)
  • 为什么是两行:`byte[] data = sb.toString().getBytes(); out.write(data, 0, data.length);` 包含在此代码示例中吗?他们的目的是什么? (2认同)
  • 但是...在上面的示例中,除了“测试字符串”之外,StringBuilder怎么有其他内容?我对此也有些困惑。如果您要将sb.toString()。getBytes()写入ZIP文件,我希望您希望它包含要压缩的文件的字节吗?还是我错过了什么? (2认同)

Siv*_*lan 133

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

Java Doc:ZipFileSystem Provider

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); 
}
Run Code Online (Sandbox Code Playgroud)

  • 这里唯一可以出现的问题是,如果你有目录,它将不起作用.因此,例如,如果在`pathInZipfile`变量中有"/dir/SomeTextFile.txt",则需要在.zip存档中创建'dir'.为此,只需在调用`Files.copy`方法之前添加下一行:`Files.createDirectories(pathInZipfile.getParent())`. (7认同)
  • 对于> = Java 7,这是正确的答案 (3认同)
  • 如果扩展名不是`.zip`,有没有办法让这个工作?我需要编写一个 `.foo` 文件,它的格式与 zip 文件完全一样,但具有不同的扩展名。我知道我可以制作一个 `.zip` 文件并重命名它,但只用正确的名称创建它会更简单。 (2认同)
  • @TroyDaniels上面的示例也使用不同的扩展名,因为它使用`jar:file:`前缀创建URI。 (2认同)

小智 33

要编写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();
Run Code Online (Sandbox Code Playgroud)


Owe*_*Cao 17

下面是压缩整个目录(包括子文件和子目录)的示例代码,它使用Java NIO的walk文件树功能.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
    public static void compress(String dirPath) {
        final Path sourceDir = Paths.get(dirPath);
        String zipFileName = dirPath.concat(".zip");
        try {
            final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
            Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
                    try {
                        Path targetFile = sourceDir.relativize(file);
                        outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
                        byte[] bytes = Files.readAllBytes(file);
                        outputStream.write(bytes, 0, bytes.length);
                        outputStream.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它,只需打电话

ZipCompress.compress("target/directoryToCompress");
Run Code Online (Sandbox Code Playgroud)

你会得到一个zip文件directoryToCompress.zip


Pav*_*vel 7

单个文件:

String filePath = "/absolute/path/file1.txt";
String zipPath = "/absolute/path/output.zip";

try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) {
    File fileToZip = new File(filePath);
    zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
    Files.copy(fileToZip.toPath(), zipOut);
}
Run Code Online (Sandbox Code Playgroud)

多个文件:

List<String> filePaths = Arrays.asList("/absolute/path/file1.txt", "/absolute/path/file2.txt");
String zipPath = "/absolute/path/output.zip";

try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) {
    for (String filePath : filePaths) {
        File fileToZip = new File(filePath);
        zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
        Files.copy(fileToZip.toPath(), zipOut);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

Spring boot控制器,将文件压缩在一个目录中,并且可以下载。

@RequestMapping(value = "/files.zip")
@ResponseBody
byte[] filesZip() throws IOException {
    File dir = new File("./");
    File[] filesArray = dir.listFiles();
    if (filesArray == null || filesArray.length == 0)
        System.out.println(dir.getAbsolutePath() + " have no file!");
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    ZipOutputStream zipOut= new ZipOutputStream(bo);
    for(File xlsFile:filesArray){
        if(!xlsFile.isFile())continue;
        ZipEntry zipEntry = new ZipEntry(xlsFile.getName());
        zipOut.putNextEntry(zipEntry);
        zipOut.write(IOUtils.toByteArray(new FileInputStream(xlsFile)));
        zipOut.closeEntry();
    }
    zipOut.close();
    return bo.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)