我有一个Java Servlet,每次调用它都会随机生成数千个String。我希望用户在调用Servlet时能够将它们保存在文件中。我不想先将文件写入磁盘或内存。用户调用servlet时,有没有一种动态写入文件的方法?谢谢
您在Servlet中生成的任何文本都可以简单地写入ServletResponse.getOutputStream()
返回的OutputStream。
如果您希望将输出作为文件下载,则可以按照此答案中的方法-https://stackoverflow.com/a/11772700/1372207
区别在于,内容类型将为text/plain
,而不是从另一个输入流中读取,您只需使用ServletOutputStream
方法将String对象直接写入print(String)
。
[如果您在提供下载服务时使用此想法将内容写入HttpServletResponse的输出流,而不是将内容保存在本地然后将文件读取为FileInputStream,则只需通过InputStream stream = new ByteArrayInputStream(exampleString.getBytes("UTF-8"));
将文件内容转换为InputStream。
以下代码部分引用了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");
}