CodeMonkey CodeMonkey -4 years ago 379
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>() {
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 -> {


return FileVisitResult.CONTINUE;


The program throws an exception,

java.nio.file.NoSuchFileException: 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 Source

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?

        .flatMap(f -> {
            try {
                return Files.lines(f, Charset.defaultCharset());
            } catch (IOException e) {
                throw new RuntimeException(e);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download