4

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

4

2 回答 2

5

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

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

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

于 2012-08-15T22:47:02.440 回答
0

如果您在提供下载服务的同时使用将内容写入 HttpServletResponse 的输出流的想法,而不是将内容保存在本地,然后以 FileInputStream 读取文件,您只需将文件内容转换为 InputStream 即可InputStream stream = new ByteArrayInputStream(exampleString.getBytes("UTF-8"));

以下代码部分引用了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");
    }
于 2020-06-05T15:15:18.670 回答