0

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.

novafluff
  • 891
  • 1
  • 12
  • 30

1 Answers1

2

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

Maciej
  • 1,954
  • 10
  • 14
  • I need to replace the Files.walk because when we put it on the server it returns a nullPointerexception, my guess is its because of some security reason so want to try the SimpleFileVisitor – novafluff Mar 16 '18 at 07:08