0

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)
bobbyrne01
  • 6,295
  • 19
  • 80
  • 150
  • possible duplicate of [How to find files that match a wildcard string in Java?](http://stackoverflow.com/questions/794381/how-to-find-files-that-match-a-wildcard-string-in-java) – Jakub Kotowski Mar 06 '14 at 11:20
  • 2
    The [Java tutorial](http://docs.oracle.com/javase/tutorial/essential/io/find.html) covers glob matching in java.nio – Romski Mar 06 '14 at 11:21

1 Answers1

0

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 )).

reto
  • 9,995
  • 5
  • 53
  • 52