Convert Files.walk to a SimplefileVisitor

171 Views Asked by At

Say that i have a thing like this

Stream<Path> files = Files.walk(Paths.get(somePath))

That i then stream through and collect

but then i want to convert it to use a SimpleFileVisitor instead because it is needed, how would i do? i have googled and tried for hours without getting anywere. Can you even use Stream with a SimpleFileVisitor? or do i need to redo the method all over? As i understand i need a couple of methods to use SimpleFileVisitor and i feel confused about it. Files.walk were very simple but it doesnt work for my intentions.

1

There are 1 best solutions below

1
On BEST ANSWER

SimpleFileVisitor approach:

In order to use SimpleFileVisitor you can use walkFileTree in the following way:

try {
      Files.walkFileTree(Paths.get("somePath"), new SimpleFileVisitor<Path>() {
          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
              System.out.println("visitFile: " + file);
              return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult visitFileFailed(Path file, IOException ex) throws IOException {
              System.out.println("visitFileFailed: " + file + " because of " + ex);
              return FileVisitResult.CONTINUE;
          }
          // etc... you can add postVisit...
      });
} catch (IOException e) {
      ...
}

This lets you to perform actions while visiting each file, but it has nothing to do with streams (well stream is a tool that you should use when it fits your needs, do not force yourself to use it when not convenient)

Stream approach:

If you prefer walk & stream you can do the following:

Stream<Path> files = Files.walk(Paths.get("somePath")).forEach(path -> doSomethingWithPath(path));

Not sure why you need SimpleFileVisitor here,as your explanation:

because it is needed

is pretty mysterious ;)