java - 我们可以在不下载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 文件夹中?
解决方案
您可以使用即时创建的所有“压缩”文件编写 Zip 文件。
由于您在谈论“下载”,我假设您在 web 应用程序中,并且希望将 zip 文件直接生成回客户端,因此您需要创建ZipOutputStream
响应流,而不是文件。例如,在Servlet
webapp 中,你会这样做:
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()
推荐阅读
- java - 当我更新我的行时,我的 MySQL 数据库的主键是否应该改变?
- ios - Xcode:找不到“XYChart/XYChartDataSourceItem.h”文件(在 iOS 中导出的 Unity 项目)
- c++ - 如何使用以“constexpr”声明的结构作为模板参数?
- powershell - Powershell翻译成python什么是变量-b和数学函数?
- flutter - Flutter 在 SharedPreferences 中编辑 Json 数据
- java - 如何使用动画定时器?
- cloud - 如何在云计算的世界中实现 mTLS
- reactjs - React-dates:样式问题以覆盖内联样式
- java - 提取多个值的控制器方法
- c# - 如何为许多微服务制作通用 Auth API?