使用 HttpServletResponse 发送 .json 文件

Sending a .json file with HttpServletResponse

我有一个 .json 文件,我想根据 Servlet 的 doGet() 方法中的特定请求将其发送到 客户端 浏览器。我的 Java 文件 IO 有点生疏,所以我很难弄清楚执行此操作的正确方法。我认为它类似于:

File myfile = new File(mypath);
OutputStream out = response.getOutputStream();
out.print(new FileInputStream(myfile).read());

或者类似的东西?

只需在 HttpServletResponse 参数上将 HTTP 响应内容类型设置为 text/plain 并写入响应。示例如下所示:

package com.giorgi.controller;

import javax.servlet.http.*;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        List<String> file = Files.readAllLines(Paths.get("c:\path\to\your\file.json"));
        String data = file.stream().collect(Collectors.joining());
        response.getWriter().write(data);
    }
}

setContentType(String type) 设置发送到客户端的响应的内容类型。