使用java在目录中列出文件时使用通配符

时间:2014-03-06 11:12:25

标签: java

为什么通配符在下面的java代码中不起作用?
我的请求看起来像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代码(DataAccess.java)。
(DataAccess.java:27)指的是for循环..

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");
            }
        });
    }

错误:

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)

1 个答案:

答案 0 :(得分:0)

方法public File[] listFiles(FilenameFilter filter)

  

如果此抽象路径名不表示目录,或者发生I / O错误,则返回null。

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

那么,你为什么会遇到这种情况呢?您正在尝试使用由shell评估的通配符char(*),但不会在new File(path)中进行评估。 new File(path)构造函数仅适用于精确路径。

DirectoryScanner(Apache Ant)或FileUtils(Apache commons-io)等问题将解决您的问题。有关可能的解决方案的更多详细信息,请参阅上面的注释,包括Java 7 NIO方法(Files.newDirectoryStream( path, glob-pattern ))。

相关问题