如何确定Path对象是文件还是目录?

时间:2018-04-01 23:44:36

标签: java path

在for循环中:如何确定Path的每个实例的类型?

package grep;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Grep {
    public static void grep(String filePath) throws IOException {
        Path myPath = Paths.get(filePath);
        try (Stream<Path> entries = Files.list(myPath)) 
        {
            List<Path> paths = entries.collect(Collectors.toList());
            for (Path path : paths) {

            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

由于您已经拥有Path,因此可以使用Path#toFile,然后检查该文件是否为File#isDirectory目录。

for (Path path : paths) {
    if (path.toFile().isDirectory()) {
        ...
    }
}

甚至更简单Files#isDirectory

for (Path path : paths) {
    if (Files.isDirectory(path)) {
        ...
    }
}