Issue
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
Solution
Any text that you generate in the Servlet can simply be written to the OutputStream returned by 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
The difference would be, that the Content-type would be text/plain
and instead of reading from another inputstream, you would just write the String objects directly to the ServletOutputStream
using the print(String)
method.
Answered By - Rajesh J Advani
Answer Checked By - Marie Seifert (JavaFixing Admin)