The old, more or less deprecated java.io.File
API had a method exists
which returned true if the File
pointed to an existing one in the file system, but I couldn't find any comparable method for java.nio.file.Path
:
scala> import java.nio.file._ import java.nio.file._ scala> val path = Paths.get("/foo") path: java.nio.file.Path = /foo scala> path. asInstanceOf compareTo endsWith getFileName getFileSystem getName getNameCount getParent getRoot isAbsolute isInstanceOf iterator normalize register relativize resolve resolveSibling startsWith subpath toAbsolutePath toFile toRealPath toString toUri
Of course I could just convert the path
back to a File
but I guess there is a better way to do that.
Edit: OK, thanks to everyone pointing out Files.exists
. Does someone know why it got more complicated (than having a simple exists
method on Path
)?
File. isDirectory() checks whether a file with the specified abstract path name is a directory or not. This method returns true if the file specified by the abstract path name is a directory and false otherwise.
To test to see if a file or directory exists, use the “ exists() ” method of the Java java. io. File class. If the exists() method returns true then the file or directory does exist and otherwise does not exists.
File exists() method in Java with examples This function determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false.
Two file paths can be compared lexicographically in Java using the method java. io. File. compareTo().
Use the Files
class:
Files.exists(path);
EDIT: to answer your subsequent question, I think the reason that the method is in another class is that Path
is an interface, and they wanted to provide an implementation (similar to putting sorting methods in the Collections
class instead of the List
interface).
Not directly related to the question, but as per ratchet freak there is an optional varags argument to the method as well, which determines how symbolic links are handled
Read the Javadocs from Oracle here.
look in the utility class Files for the package:
Files.exists(Path path,LinkOption... options)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With