首页 > 解决方案 > 我们可以在不下载java中的txt文件的情况下为多个txt文件下载Zip吗?

问题描述

我们可以写入多个txt文件并直接以zip格式下载(不下载txt文件)

当我们写入文件时,它是在物理文件中完成的。但是当我们要创建该引用的 zip 时,它会考虑目标文件。

有什么方法可以将数据存储在目标文件中,然后将其下载为 zip .??

File file = new File("/Users/VYadav/Desktop/lex/sitemap.txt");  // creates local object
String zipFileName = "/Users/VYadav/Desktop/lex/zipname.zip";

FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);

PrintWriter pw=new PrintWriter(file);  // creates a physical file on disk
pw.write("Hii");   // writes in physical file
pw.flush();

ZipEntry ze = new ZipEntry(file.getName()); // Reads from local object (here data is not present) 

zos.putNextEntry(ze);

此代码的输出将是一个以“Hii”为数据的 txt 文件和一个包含空白 txt 文件的 zip 文件。

因为文件是从objet放入zip条目的。

有什么方法可以更新对象中的数据然后下载到 zip 文件夹中?

标签: javafilestream

解决方案


您可以使用即时创建的所有“压缩”文件编写 Zip 文件。

由于您在谈论“下载”,我假设您在 web 应用程序中,并且希望将 zip 文件直接生成回客户端,因此您需要创建ZipOutputStream响应流,而不是文件。例如,在Servletwebapp 中,你会这样做:

response.setContentType("application/zip");

ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
PrintWriter out = new PrintWriter(zos);

zos.putNextEntry(new ZipEntry("Foo.txt"));
// write content of Foo.txt here, e.g.
out.println("Hello Foo");
out.flush();

zos.putNextEntry(new ZipEntry("Bar.txt"));
// write content of Bar.txt here, e.g.
out.println("Hello Bar");
out.flush();

zos.putNextEntry(new ZipEntry("Baz.png"));
// write content of Baz.png here, e.g. copy bytes from file on classpath
try (InputStream in = this.getClass().getResourceAsStream("logo.png")) {
    byte[] buf = new byte[8192];
    for (int len; (len = in.read(buf)) > 0; )
        zos.write(buf, 0, len);
}

// Complete the zip file.
zos.finish(); // or zos.close()

推荐阅读