简体   繁体   English

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

[英]Using wildcard when listing files in directory with java

Why does a wildcard not work in java code below? 为什么通配符在下面的Java代码中不起作用?
My request looks like http://localhost:8080/App/DataAccess?location=Dublin 我的请求看起来像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). Servlet代码(DataAccess.java)。
(DataAccess.java:27) refers to the for loop .. (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");
            }
        });
    }

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) 方法public File[] listFiles(FilenameFilter filter)

Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs. 如果此抽象路径名不表示目录,或者发生I / O错误,则返回null。

( http://docs.oracle.com/javase/7/docs/api/java/io/File.html ) 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) . 您正在尝试使用由外壳程序评估但不能在new File(path)评估的通配符char( * new File(path) The new File(path) constructor only works for exact paths. new File(path)构造函数仅适用于确切路径。

Things like DirectoryScanner (Apache Ant) or FileUtils (Apache commons-io) will solve your problem. DirectoryScanner (Apache Ant)或FileUtils (Apache commons-io)之类的东西可以解决您的问题。 See the comments above for further details on possible solutions, including the Java 7 NIO approach ( Files.newDirectoryStream( path, glob-pattern ) ). 有关可能的解决方案的更多详细信息,请参见上面的注释,包括Java 7 NIO方法( Files.newDirectoryStream( path, glob-pattern ) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM