File.exists() works but Files.readAllBytes() fails with NoSuchFileException

2.4k views Asked by At

I am trying to read a text file in Java and I get NoSuchFileException.

I tried to check if the file path exists and it returns true. Here is my code.

            final File actualFile = new File(filePath);
            if (actualFile.exists()) {
                log.info("ACTUALFILE exists");
            } else {
                log.info("ACTUALFILE does not exist");
            }

            String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

I get the following exception.

ACTUALFILE exists

java.nio.file.NoSuchFileException: my-file.json
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86) ~[?:1.8.0_201]
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102) ~[?:1.8.0_201]
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107) ~[?:1.8.0_201]
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214) ~[?:1.8.0_201]
at java.nio.file.Files.newByteChannel(Files.java:361) ~[?:1.8.0_201]
at java.nio.file.Files.newByteChannel(Files.java:407) ~[?:1.8.0_201]
at java.nio.file.Files.readAllBytes(Files.java:3152) ~[?:1.8.0_201]

Why is Files.readAllBytes() not able to find the file? Am I missing something here?

[Update 1] Here is the file permissions -rwxr-xr-x.

0

There are 0 answers