我真正喜欢的Ruby的一个特性是ability to tap into call chains。它提供了一种简单的方法来调试管道中正在发生的事情。我使用tap
模拟map
:
/** Searches recursively and returns the path to the dir that has a file with given extension,
* null otherwise.
* Returns the given dir if it has a file with given extension.
* @param dir Path to the start folder
* @param ext String denotes the traditional extension of a file, e.g. "*.gz"
* @return {@linkplain Path} of the folder containing such a file, null otherwise
*/
static Path getFolderWithFilesHavingExtension(Path dir, String ext) {
Objects.requireNonNull(dir); // ignore the return value
Objects.requireNonNull(ext); // ignore the return value
try {
Optional<Path> op = Files.walk(dir, 10).map((t) -> {
System.out.println("tap: " + t.endsWith(ext));
System.out.println("tap: " + t.toString().endsWith(ext));
return t;
}).filter(p -> p.toString().endsWith(ext)).limit(1).findFirst();
if (op.isPresent())
return op.get().getParent();
} catch (IOException e) {
return null; // squelching the exception is okay? //TODO
}
return null; // no such files found
}
这实际上帮助我解决了一个错误,即我正在执行Path::endsWith
而不是String::endsWith
,以查看文件名是否以特定扩展名结尾。
在Java 8中有更好的(惯用的)方法吗?
答案 0 :(得分:4)
您可以使用.peek(System.out::println)
或.peek(t -> "tap: " +t.endsWith(ext))