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

0

6

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.

Cannabis answered 23/11, 2020 at 13:23 Comment(7)
Are you sure it's not a directory? File.exists will return true on directories, but you can't read bytes from them.Epitasis
Do you have read access to the file?Somniferous
Are you running it via any editor or command line? And the file is in the root folder of the project, right?Luedtke
Yes, the file is in the root folder of the project. It is an actual json.file. I have -rwxr-xr-x for the File permissions.Cannabis
I think the problem may be Paths.get(filePath). Try actualFile.toPath() insteadEpitasis
try using this: String content = new String(Files.readAllBytes(new File(filePath).toPath()), StandardCharsets.UTF_8);Dickerson
Use the Path, Paths, and Files classes only. Don’t use java.io.File at all, as it is old and obsolete. Test for the file’s existence using Files.exists or Files.isReadable (in the java.nio.file package), not File.exists (in the java.io package).Onward

© 2022 - 2024 — McMap. All rights reserved.