I am trying to list the files in a folder but it produces a null pointer exception this is the code
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());
}
}
When i print the path it gives the correct path:
like D:\apache-tomcat-8.5.24\webapps\JaasLogin\JaasLogin\user-files
.
i am new to java
Context path: /jaasLogin
but when i give path directly like "D:\\apache-tomcat-8.5.24\\webapps\\JaasLogin\\JaasLogin\\user-files"
it will works
Output i got
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)