CodeMonkey CodeMonkey - 3 months ago 65
Java Question

java.nio.file.NoSuchFileException: While reading files in Java

I'm using the following code to walk a directory and read a file line by line.

public void read() throws IOException {
Files.walkFileTree(Paths.get(this.dir), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try (Stream<String> lines = Files.lines(Paths.get(String.valueOf(file.getFileName())), Charset.defaultCharset())) {
lines.forEachOrdered(line -> {

System.out.println(line);

});
}
return FileVisitResult.CONTINUE;
}
});

}


The program throws an exception,

java.nio.file.NoSuchFileException: 1472081748921.txt


1472081748921.txt
is the name of the first file in the directory, So I guess it's going into the directory, but despite the file being present is not reading it. What am I doing wrong here.

Answer

Your issue is here:

Files.lines(Paths.get(String.valueOf(file.getFileName())), Charset.defaultCharset()))

I have no idea why you are doing this! Replace with:

Files.lines(file, Charset.defaultCharset())

Why not use Files.list?

Files.list(dir)
        .filter(Files::isRegularFile)
        .flatMap(f -> {
            try {
                return Files.lines(f, Charset.defaultCharset());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        })
        .forEach(System.out::println);
Comments