getResource()nullPointerException

时间:2019-02-08 12:47:44

标签: java embedded-resource

我正在尝试获取Java中本地JSON文件的内容。相反,我得到以下堆栈跟踪:

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)

我已经确保文件coordinates.jsonWebservice.java文件位于同一目录中。我知道this question,但是答案并不能解决我的问题。这是我的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());
    }
}

1 个答案:

答案 0 :(得分:0)

尝试使用getSystemResource()方法

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

或@LaksithaRanasingha在评论中如何提及它,并在开头添加/

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

这也许很有用Class.getResource and ClassLoader.getSystemResource: is there a reason to prefer one to another?