我正在尝试列出文件夹中的文件,但是会产生空指针异常 这是代码
String url=req.getRequestURI();
String path=session.getServletContext().getRealPath(url);
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {//this line is producing nullpointer exception
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
当我打印路径时,它将给出正确的路径:
像D:\apache-tomcat-8.5.24\webapps\JaasLogin\JaasLogin\user-files
。
我是Java新手
上下文路径:/ jaasLogin
但是当我直接像"D:\\apache-tomcat-8.5.24\\webapps\\JaasLogin\\JaasLogin\\user-files"
那样给出路径时,它将起作用
我得到的输出
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [userfileserv] in context with path [/JaasLogin] threw exception
java.lang.NullPointerException
at myPackage.UserFileServ.doGet(UserFileServ.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
答案 0 :(得分:0)
如File.listFiles()的Javadoc所述:
如果此抽象路径名不表示目录,则返回null;或者 如果发生I / O错误。
因此,为了防止NPE,请执行以下操作:
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
}
else {
System.out.println("Could not read " + folder.getName());
}