Java servlet和IO:创建文件而不保存到磁盘并将其发送给用户 [英] Java servlet and IO: Create a file without saving to disk and sending it to the user

查看:1063
本文介绍了Java servlet和IO:创建文件而不保存到磁盘并将其发送给用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能帮助我解决文件创建/回复问题。
我知道如何创建和保存文件。我知道如何通过ServletOutputStream将该文件发送回用户。

I`m hoping can help me out with a file creation/response question. I know how to create and save a file. I know how to send that file back to the user via a ServletOutputStream.

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

But what I need is to create a file, without saving it on the disk, and then send that file via the ServletOutputStream.

上面的代码解释了我所拥有的部分。任何帮助赞赏。在此先感谢。

The code above explains the parts that I have. Any help appreciated. Thanks in Advance.

// 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);


推荐答案

您无需保存文件,只需使用ByteArray流,尝试这样的事情:

You don't need to save off a file, just use a ByteArray stream, try something like this:

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

或者,更简单,只需:

stream.write(text .getBytes());

cHao 建议,使用 text.getBytes(UTF-8)或类似的东西来指定除系统默认值之外的字符集。可用的字符集列表可在 Charset

As cHao suggests, use text.getBytes("UTF-8") or something similar to specify a charset other than the system default. The list of available charsets is available in the API docs for Charset.

这篇关于Java servlet和IO:创建文件而不保存到磁盘并将其发送给用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆