我有以下目录结构:
/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/1.2.3/
/path/to/stuff/org/foo/bar/1.2.3/myfile.ext
/path/to/stuff/org/foo/bar/1.2.4/
/path/to/stuff/org/foo/bar/1.2.4/myfile.ext
/path/to/stuff/org/foo/bar/blah/
/path/to/stuff/org/foo/bar/blah/2.1/
/path/to/stuff/org/foo/bar/blah/2.1/myfile.ext
/path/to/stuff/org/foo/bar/blah/2.2/
/path/to/stuff/org/foo/bar/blah/2.2/myfile.ext
Run Code Online (Sandbox Code Playgroud)
我想得到以下输出:
/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/blah/
Run Code Online (Sandbox Code Playgroud)
我有以下代码(下面),这是低效的,因为它打印出来:
/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/blah/
/path/to/stuff/org/foo/bar/blah/
Run Code Online (Sandbox Code Playgroud)
这是Java代码:
public class LocatorTest
{
@Test
public void testLocateDirectories()
throws IOException
{
long startTime = System.currentTimeMillis();
Files.walk(Paths.get("/path/to/stuff/"))
.filter(Files::isDirectory)
.forEach(Foo::printIfArtifactVersionDirectory);
long endTime = System.currentTimeMillis();
System.out.println("Executed in " + (endTime - startTime) + " ms.");
}
static class Foo
{
static void printIfArtifactVersionDirectory(Path path)
{
File f = path.toAbsolutePath().toFile();
List<String> filePaths = Arrays.asList(f.list(new MyExtFilenameFilter()));
if (!filePaths.isEmpty())
{
System.out.println(path.getParent());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
过滤器:
public class MyExtFilenameFilter
implements FilenameFilter
{
@Override
public boolean accept(File dir, String name)
{
return name.endsWith(".ext");
}
}
Run Code Online (Sandbox Code Playgroud)
a b*_*ver 35
Files.walk(Paths.get("/path/to/stuff/"))
.filter(p -> p.toString().endsWith(".ext"))
.map(p -> p.getParent().getParent())
.distinct()
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
这将过滤所有具有扩展名的文件并获取其目录的父路径.distinct确保每个路径仅使用一次.
| 归档时间: |
|
| 查看次数: |
37425 次 |
| 最近记录: |