2017-04-12 37 views
1

以下代碼顯示文件。java stream filter not displayed output

Files.walk(Paths.get("E:\\pdf")) 
       .map(path -> path.toAbsolutePath().getFileName()) 
         .forEach(System.out::println); 

但是這個dosen't顯示pdf輸出爲什麼它不工作?

Files.walk(Paths.get("E:\\pdf")) 
       .map(path -> path.toAbsolutePath().getFileName()) 
        .filter(path -> path.endsWith(".pdf")) 
         .forEach(System.out::println); 

回答

4

由於this question指出並this article解釋,path.endsWith()只有在有最終的目錄分隔後的一切完全吻合返回true:

如果你需要比較java.io.file.Path對象,做到心中有數Path.endsWith(String)只會匹配您原始路徑中Path對象的另一個子元素,而不是路徑名字符串部分!如果您想匹配字符串名稱部分,則需要先撥打Path.toString()

速戰速決是更換過濾網:

path.toString().toLowerCase().endsWith(".pdf"); 

還有的Java NIO的PathMatcher,這是爲應對路徑製成。這裏有一個例子:

final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.pdf"); 

您可以使用:

.filter(path -> matcher.matches(path)) 

Finding Files教程瞭解更多詳情。