2014-03-06 65 views
0

为什么通配符在下面的java代码中不起作用?
我的要求看起来像http://localhost:8080/App/DataAccess?location=Dublin使用通配符列出与java目录中的文件时

[email protected]:~$ 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) 
+0

[如何找到与Java中的通配符字符串匹配的文件?](http://stackoverflow.com/questions/794381/how-to-find-files-that-match-a-wildcard-string -in-java) –

+2

[Java教程](http://docs.oracle.com/javase/tutorial/essential/io/find.html)涵盖java.nio中的glob匹配 – Romski

回答

0

的方法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

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

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

+0

使用的'DirectoryScanner'(Apache Ant) ,工作过一种享受..谢谢 – bobbyrne01

+0

不客气 – reto