Why does a wildcard not work in java code below?
My request looks like http://localhost:8080/App/DataAccess?location=Dublin
rob@work:~$ ls /usr/local/CustomAppResults/Dublin/*/.history
/usr/local/CustomAppResults/Dublin/team1/.history
/usr/local/CustomAppResults/Dublin/team2/.history
/usr/local/CustomAppResults/Dublin/team3/.history
Servlet code (DataAccess.java).
(DataAccess.java:27)
refers to the for loop ..
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File[] files = finder("/usr/local/CustomAppResults/" +
request.getParameter("location") + "/*/");
for (int i = 0; i < files.length; i++){
System.out.println(files[i].getName());
}
}
private File[] finder(String dirName) {
File dir = new File(dirName);
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith(".history");
}
});
}
Error:
The server encountered an internal error that prevented it
from fulfilling this request.
java.lang.NullPointerException
com.example.servlets.DataAccess.doGet(DataAccess.java:27)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
The method public File[] listFiles(FilenameFilter filter)
Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
( http://docs.oracle.com/javase/7/docs/api/java/io/File.html )
So, why do you get this situation? You are trying to use a wildcard char ( *
) that is evaluated by your shell, but won't be evaluated in new File(path)
. The new File(path)
constructor only works for exact paths.
Things like DirectoryScanner
(Apache Ant) or FileUtils
(Apache commons-io) will solve your problem. See the comments above for further details on possible solutions, including the Java 7 NIO approach ( Files.newDirectoryStream( path, glob-pattern )
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.