创建一个文本文件以使用 Java 即时下载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11978356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:08:20  来源:igfitidea点击:

Create a text file for download on the fly with Java

javaservlets

提问by Oscar

I have a Java Servlet that generates randomly thousands of Strings every time is called. I want the user to be able to get them in a file when he calls the Servlet. I don't want to write first the file on disk or memory. Is there a way to write the file on the fly when the user calls the servlet? Thanks

我有一个 Java Servlet,每次调用时都会随机生成数千个字符串。我希望用户在调用 Servlet 时能够将它们保存在文件中。我不想先将文件写入磁盘或内存。当用户调用 servlet 时,有没有办法即时写入文件?谢谢

回答by Rajesh J Advani

Any text that you generate in the Servlet can simply be written to the OutputStream returned by ServletResponse.getOutputStream().

您在 Servlet 中生成的任何文本都可以简单地写入由 返回的 OutputStream ServletResponse.getOutputStream()

If you want the output to be downloadable as a file, you can follow the approach in this answer - https://stackoverflow.com/a/11772700/1372207

如果您希望输出可作为文件下载,您可以按照此答案中的方法进行操作 - https://stackoverflow.com/a/11772700/1372207

The difference would be, that the Content-type would be text/plainand instead of reading from another inputstream, you would just write the String objects directly to the ServletOutputStreamusing the print(String)method.

不同之处在于,内容类型将是text/plain,而不是从另一个输入流读取,您只需将 String 对象直接写入ServletOutputStreamusingprint(String)方法。