ServletContext#getResourceAsStream()返回null

时间:2013-09-19 14:27:07

标签: servlets

任何人都可以回答这个问题吗?不知道为什么我在尝试执行以下程序时会收到NullPointerException。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    response.setContentType("image/jpeg");
    ServletContext ctx = getServletContext();
    InputStream is = ctx.getResourceAsStream("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg"); --> The picture exists at this location
    OutputStream os = response.getOutputStream();
    int read = 0;
    byte[] bytes = new byte[1024];
    System.out.println("bytes :" + bytes);
    while((read = is.read(bytes)) != -1) -- Error at this line
    {
    System.out.println("read :" +read);
    os.write(bytes, 0, read);
    }
    os.flush();
    os.close();
    }

在tomcat-Apache中运行时遇到以下错误。

bytes :[B@158f9d3
Sep 19, 2013 7:23:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Newest threw exception
java.lang.NullPointerException
        at com.examples.Newest.doPost(Newest.java:69)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:873)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:662)

1 个答案:

答案 0 :(得分:0)

InputStream is = ctx.getResourceAsStream("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg"); --> The picture exists at this location

不是您访问文件系统上文件的方式。通过该方法调用,您将尝试获取resource from the context root。并且,因为您显然没有相对于上下文根的名为C:/Users/Public/Pictures/Sample Pictures/Desert.jpg的资源,所以它返回null

使用Java 7的NIO

Path path = Paths.get("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg");
InputStream is = Files.newInputStream(path);