【问题标题】:Java servlet and IO: Create a file without saving to disk and sending it to the userJava servlet 和 IO:创建文件而不保存到磁盘并将其发送给用户
【发布时间】:2023-12-14 23:19:02
【问题描述】:

我希望可以帮助我解决文件创建/响应问题。 我知道如何创建和保存文件。我知道如何通过 ServletOutputStream 将该文件发回给用户。

但我需要创建一个文件,而不是将其保存在磁盘上,然后通过 ServletOutputStream 发送该文件。

上面的代码解释了我所拥有的部分。任何帮助表示赞赏。提前致谢。

// This Creates a file
//
String   text = "These days run away like horses over the hill";
File     file = new File("MyFile.txt");
Writer writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
writer.close();

// Missing link goes here
//

// This sends file to browser
//
InputStream inputStream = null;
inputStream = new FileInputStream("C:\\MyFile.txt");

byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();

int bytesRead;
while (  (bytesRead = inputStream.read(buffer)) != -1)
   baos.write(buffer, 0, bytesRead);

response.setContentType("text/html");
response.addHeader("Content-Disposition", "attachment; filename=Invoice.txt");

byte[] outBuf = baos.toByteArray();
stream = response.getOutputStream();
stream.write(outBuf);

【问题讨论】:

  • 谢谢德科。我认为我的问题没有很好地提出。您的评论正是我想做的,但我不知道该怎么做。

标签: java servlets io response outputstream


【解决方案1】:

您不需要保存文件,只需使用 ByteArray 流,试试这样:

inputStream = new ByteArrayInputStream(text.getBytes());

或者,更简单,就是这样做:

stream.write(text.getBytes());

正如cHao 建议的那样,使用text.getBytes("UTF-8") 或类似的东西来指定系统默认以外的字符集。 Charset 的 API 文档中提供了可用字符集的列表。

【讨论】:

  • 指定编码,当然...text.getBytes("UTF-8"),例如。