Issue
I have a .json file that I would like to send to the client browser on a specific request inside the Servlet's doGet()
method. My Java file IO is a little rusty so I'm having a little trouble figuring out what is the right way to do this. I figure it's something like:
File myfile = new File(mypath);
OutputStream out = response.getOutputStream();
out.print(new FileInputStream(myfile).read());
or something close-ish to that?
Solution
Just set your HTTP Response content type to text/plain
on your HttpServletResponse
argument and write into response. Example would look like this:
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) sets the content type of the response being sent to the client.
Answered By - Giorgi Tsiklauri
Answer Checked By - David Goodson (JavaFixing Volunteer)