The java.nio.file.Files
API is a really nice improvement over the old java.io.File
class, but one detail strikes me as odd; with the exception of delete()
no methods document that they may throw NoSuchFileException
, and even delete()
says this is optional.
I'd like to be able to differentiate between failures due to missing files and other IO issues, but it seems this isn't guaranteed to be possible.
The alternative of calling Files.exists()
and the like beforehand risks a race-condition if the file is created in between the two operations.
Can I expect methods in Files
will raise a NoSuchFileException
when appropriate? If so, where is this documented? If not, how can I safely determine the failure is due to a missing file?
Example: On Windows 7 with Java 7.0.02 the Files.readAllLines()
method does raise a NoSuchFileException
, though it's not explicitly documented to do so:
Files.readAllLines(Paths.get("foo"), StandardCharsets.UTF_8)
java.nio.file.NoSuchFileException: foo at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:229) at java.nio.file.Files.newByteChannel(Files.java:315) at java.nio.file.Files.newByteChannel(Files.java:361) at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:380) at java.nio.file.Files.newInputStream(Files.java:106) at java.nio.file.Files.newBufferedReader(Files.java:2660) at java.nio.file.Files.readAllLines(Files.java:2993)