2014-03-06 63 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