Search code examples
javaembedded-resource

getResource() nullPointerException


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());
    }
}

Solution

  • 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?