0

I'm going through a file directory recursively using a FileVisitor object. I did override the preVisitDirectory method, but I want to assign its dir parameter to a String which is located in the outer scope of this overridden method and FileVisitor object. This is my code:

        FileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
              String cur_dir = "";
              FileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
              @Override
              public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs)
                  throws IOException {
//              System.out.println("DIRECTORY NAME:"+ dir.getFileName() 
//                                 + " LOCATION:"+ dir.toFile().getPath());
                cur_dir  = dir.toFile().getPath();
                System.out.println("cur_dir: " + cur_dir);
                return FileVisitResult.CONTINUE;
              }
               
              @Override
              public FileVisitResult visitFile(Path visitedFile,BasicFileAttributes fileAttributes)
                  throws IOException {
                System.out.println("FILE NAME: "+ visitedFile.getFileName());
                return FileVisitResult.CONTINUE;
              }
            };
            
            FileSystem fileSystem = FileSystems.getDefault();
            String path = System.getProperty("user.home")+"/UTP8dir";
            Path rootPath = fileSystem.getPath(path);
            try {
              Files.walkFileTree(rootPath, simpleFileVisitor);
            } catch (IOException ioe) {
              ioe.printStackTrace();
            }

It obviously gives me a compilation error about "enclosing scope", I understand why this happens, but I don't know what's the way to do it though, how can I assign subdirectories's names to an outer-scope String for each directory?

My ultimate goal is to write the contents of all .txt files I find during this to some String.

Javadkhan
  • 159
  • 2
  • 12

1 Answers1

0

Given the result is that you want to return a concatenation of all the contents in all the files, you might be better using a stream from Files.walk instead. From this you can then collect all lines and allows you the opportunity to filter file names and lines potentially providing other transforms.

try (var walker = Files.walk(Path.of(System.getProperty("user.home") + "/UTP8dir"))) {
    var contents = walker
        .filter(Files::isRegularFile)
        .flatMap(f -> {
            try {
                return Files.lines(f);
            } catch (IOException ioe) {
                throw new UncheckedIOException(ioe);
            }
        })
        .collect(joining("\n"));
}

I have done a lot of testing for performance characteristics on this in the past, see this question and this Github project with tests.

Brett Ryan
  • 26,937
  • 30
  • 128
  • 163