getResource() 空指针异常
getResource() nullPointerException
我正在尝试获取 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.json
文件与 Webservice.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());
}
}
尝试使用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?
我正在尝试获取 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.json
文件与 Webservice.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());
}
}
尝试使用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?