java生成文件 不保存,Java servlet和IO:创建文件而不保存到磁盘并将其发送给用户...

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.

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

解决方案

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值