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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
SyncMaster
  • 9,754
  • 34
  • 94
  • 137
  • 5
    Are you sure it's not a directory? `File.exists` will return `true` on directories, but you can't read bytes from them. – Jeroen Steenbeeke Nov 23 '20 at 13:27
  • Do you have read access to the file? – samabcde Nov 23 '20 at 13:36
  • Are you running it via any editor or command line? And the file is in the root folder of the project, right? – KnockingHeads Nov 23 '20 at 13:40
  • 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. – SyncMaster Nov 23 '20 at 13:42
  • 4
    I think the problem may be `Paths.get(filePath)`. Try `actualFile.toPath()` instead – Jeroen Steenbeeke Nov 23 '20 at 13:45
  • try using this: `String content = new String(Files.readAllBytes(new File(filePath).toPath()), StandardCharsets.UTF_8);` – Mustafa Poya Nov 23 '20 at 13:54
  • 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](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/nio/file/Files.html#exists(java.nio.file.Path,java.nio.file.LinkOption...)) or [Files.isReadable](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/nio/file/Files.html#isReadable(java.nio.file.Path)) (in the java.nio.file package), not File.exists (in the java.io package). – VGR Nov 23 '20 at 14:57

0 Answers0