我们可以不下载Java中的txt文件而下载多个txt文件的Zip吗?

时间:2019-06-09 16:51:41

标签: java file stream

我们可以写入多个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文件夹中?

1 个答案:

答案 0 :(得分:0)

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

由于您正在谈论“下载”,因此我假设您在一个Web应用程序中,并且想要直接将zip文件生成回客户端,因此您需要针对以下内容创建ZipOutputStream响应流,而不是文件。例如。在Servlet网络应用中,您可以这样做:

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