0

Given the below directory structure:

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

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. Just seems convoluted.

The Unix command find dir2 is pretty spot on.

PaulM
  • 345
  • 2
  • 11

2 Answers2

2

You have a base directory and a Collection<File>. You can use Path.relativize to get the relative path from one to the other.

This example, given /dir1 and /dir1/foo/bar/baz, will result in foo/bar/baz without any fragile string operations:

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()));
  }
}
that other guy
  • 116,971
  • 11
  • 170
  • 194
1

Since you're using the Java 7 Path, you might as well use the Java 7 Files too.

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 Windows1)

dir2\dirA\file3
dir2\file1
dir2\file2

1) On Linux, the paths would have forward slash instead of backslash.

Andreas
  • 154,647
  • 11
  • 152
  • 247