2

I am trying to get the contents of a local JSON file in Java. Instead I am getting the following stacktrace:

java.lang.NullPointerException
    fi.avaliaho.ottoautomaatitv2.Webservice.doGet(Webservice.java:24)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:352)
    org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:171)

I already made sure that the file coordinates.json is located in the same directory as the Webservice.java file. I am aware of this question, but the answers do not solve my problem. Here is my servlet:

import java.net.URL;
import java.io.*;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Webservice extends HttpServlet {

    URL path = null;
    Reader file = null;
    BufferedReader input = null;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        path = Webservice.class.getResource("coordinates.json");
        file = new FileReader(path.getFile());
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
aleksejjj
  • 1,405
  • 2
  • 18
  • 28
  • have you tried prepending / like `Webservice.class.getResource("/coordinates.json")`? – Laksitha Ranasingha Feb 08 '19 at 12:53
  • `I already made sure that the file coordinates.json is located in the same directory as the Webservice.java`. Is the class-file located in the same directory as the source? If not put the json-file into the directory where the classes are (that's where the class path in general points to) – Lothar Feb 08 '19 at 12:55

1 Answers1

1

Try to use getSystemResource() method

path = ClassLoader.getSystemResource("coordinates.json")

or how it was mentioned by @LaksithaRanasingha in comments add / in the begining:

path = Webservice.class.getResource("/coordinates.json");

Also this might be useful Class.getResource and ClassLoader.getSystemResource: is there a reason to prefer one to another?

Ruslan
  • 6,090
  • 1
  • 21
  • 36