Tôi đang cố gắng viết một ứng dụng để sử dụng phương thức Files.find
trong đó.Làm thế nào để sử dụng phương pháp Java 8 `Files.find`?
Dưới chương trình hoạt động hoàn hảo:
package ehsan;
/* I have removed imports for code brevity */
public class Main {
public static void main(String[] args) throws IOException {
Path p = Paths.get("/home/ehsan");
final int maxDepth = 10;
Stream<Path> matches = Files.find(p,maxDepth,(path, basicFileAttributes) -> String.valueOf(path).endsWith(".txt"));
matches.map(path -> path.getFileName()).forEach(System.out::println);
}
}
này hoạt động tốt và mang lại cho tôi một danh sách các tập tin kết thúc với .txt
(tập tin văn bản aka):
hello.txt
...
Nhưng bên dưới chương trình không hiển thị bất cứ điều gì:
package ehsan;
public class Main {
public static void main(String[] args) throws IOException {
Path p = Paths.get("/home/ehsan");
final int maxDepth = 10;
Stream<Path> matches = Files.find(p,maxDepth,(path, basicFileAttributes) -> path.getFileName().equals("workspace"));
matches.map(path -> path.getFileName()).forEach(System.out::println);
}
}
Nhưng nó không hiển thị bất cứ điều gì :(
Đây là thư mục nhà của tôi hiearchy (ls
kết quả):
blog Projects
Desktop Public
Documents Templates
Downloads The.Purge.Election.Year.2016.HC.1080p.HDrip.ShAaNiG.mkv
IdeaProjects The.Purge.Election.Year.2016.HC.1080p.HDrip.ShAaNiG.mkv.aria2
Music Videos
Pictures workspace
Vì vậy, whats đi sai với path.getFileName().equals("workspace")
?
Bạn đã cố gắng sử dụng Trình gỡ lỗi chưa? – Jens
Hãy coi chừng rằng bạn phải đóng 'Stream' mà' Files.find (...) 'trả về, nếu không bạn sẽ bị rò rỉ tài nguyên; [Tài liệu API] (http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#find-java.nio.file.Path-int-java.util. function.BiPredicate-java.nio.file.FileVisitOption ...-) giải thích điều này (xem nó nói "cấu trúc try-with-resources nên được sử dụng ..."). – Jesper
IntelliJ có trình gỡ rối rất tốt (Tôi không biết ý bạn là gì với "trình sửa lỗi VS"). Bạn cũng có thể đặt các câu lệnh 'System.out.println (...) 'vào các điểm trong mã của bạn để xem điều gì đang xảy ra. – Jesper