简体   繁体   English

在 Java 7 中,列出具有“相对路径”的文件

[英]In Java 7, list files with "relative path"

Given the below directory structure:鉴于以下目录结构:

/dir1
/dir1/dir2
/dir1/dir2/file1
/dir1/dir2/file2
/dir1/dir2/dirA/file3

someFunction("dir2") someFunction("dir2")

desired output:所需的输出:

dir2/file1
dir2/file2
dir2/dirA/file3

I am using FileUtils.listFiles and Paths and then String manipulation, but wondering if better way.我正在使用 FileUtils.listFiles 和 Paths,然后使用字符串操作,但想知道是否有更好的方法。 Just seems convoluted.只是看起来很复杂。

The Unix command find dir2 is pretty spot on. Unix 命令find dir2非常合适

You have a base directory and a Collection<File> .您有一个基本目录和一个Collection<File> You can use Path.relativize to get the relative path from one to the other.您可以使用Path.relativize获取从一个到另一个的相对路径。

This example, given /dir1 and /dir1/foo/bar/baz , will result in foo/bar/baz without any fragile string operations:这个例子,给定/dir1/dir1/foo/bar/baz ,将导致foo/bar/baz没有任何脆弱的字符串操作:

import java.io.*;
import java.nio.file.*;

class Foo {
  public static void main(String[] args) throws Exception {
    Path base = Paths.get("/dir1");
    File f = new File("/dir1/foo/bar/baz");
    System.out.println(base.relativize(f.toPath()));
  }
}

Since you're using the Java 7 Path , you might as well use the Java 7 Files too.由于您使用的是 Java 7 Path ,您也可以使用 Java 7 Files

static void someFunction(String dir) throws IOException {
    Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println(file);
            return FileVisitResult.CONTINUE;
        }
    });
}

Test测试

someFunction("dir2");

Output (on Windows 1 )输出(在 Windows 1 上

dir2\dirA\file3
dir2\file1
dir2\file2

1) On Linux, the paths would have forward slash instead of backslash. 1) 在 Linux 上,路径会有正斜杠而不是反斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM