Java servlet 和 IO:创建文件而不保存到磁盘并将其发送给用户 [英] Java servlet and IO: Create a file without saving to disk and sending it to the user
问题描述
我希望可以帮助我解决文件创建/响应问题.我知道如何创建和保存文件.我知道如何通过 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());
或者,更简单的做法是:
Or, even simpler, just do:
stream.write(text.getBytes());
正如 cHao 建议的那样,使用 text.getBytes("UTF-8")
或类似于指定系统默认值以外的字符集.可用字符集列表可在 字符集.
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屋!