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
.
File.exists
will returntrue
on directories, but you can't read bytes from them. – Epitasis-rwxr-xr-x
for the File permissions. – CannabisPaths.get(filePath)
. TryactualFile.toPath()
instead – EpitasisString content = new String(Files.readAllBytes(new File(filePath).toPath()), StandardCharsets.UTF_8);
– DickersonPath
,Paths
, andFiles
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