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
-
You don't want it on disk *or* in memory? Where would this file exist long enough for the user to download it? Could you elaborate on this, please? – Makoto Aug 15 '12 at 22:42
-
1@Makoto Well I thought that I could write the bytes directly to the outputStream if that means being in memory then it's fine. – Oscar Aug 15 '12 at 22:48
-
1@Makoto All the contents in the file don't have to exist in memory at the same time. Once written to the outputstream, the JVM would be free to clear up the memory used by the strings, assuming there are no references to them in any classes at that point in time. – Rajesh J Advani Aug 15 '12 at 22:54
2 Answers
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.

- 1
- 1

- 5,585
- 2
- 23
- 35
-
Should I use a StringBuffer to append all my String and then at the end just to do this: out.write(myStringBuffer.toString().getBytes()); – Oscar Aug 15 '12 at 22:56
-
I wouldn't recommend it. That way you'd be unnecessarily using up memory to hold the entire "file" in memory. Just write the strings to the outputstream as you generate them, so that you can release the references to them and let the JVM reclaim the memory they use. – Rajesh J Advani Aug 15 '12 at 23:00
-
Ok so for example should I just to use the print method if I am using a ServletOutputStream ? – Oscar Aug 15 '12 at 23:04
If you use the idea to write content to HttpServletResponse's output stream while offering download service, rather than saving the content locally and then reading the file as FileInputStream, you can just convert the file content to InputStream by InputStream stream = new ByteArrayInputStream(exampleString.getBytes("UTF-8"));
.
The following code partially references https://www.codejava.net/java-ee/servlet/java-servlet-download-file-example.
public void doDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileName = "xxx.txt";
String fileContent = "";
// get absolute path of the application
ServletContext context = request.getServletContext();
// get MIME type of the file
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
setResponseHeader(response, fileName, mimeType, (int) fileContent.length());
InputStream inputStream = new ByteArrayInputStream(fileContent.getBytes("UTF-8"));
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
private void setResponseHeader(HttpServletResponse response, String fileName, String mimeType, Integer fileLength) {
response.setContentType(mimeType);
response.setContentLength(fileLength);
response.setContentType("application/octet-stream; charset=UTF-8");
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
}

- 28,441
- 6
- 34
- 52