How to check if a path points to an existing file with Java 7's new File API?

soc picture soc · May 21, 2011 · Viewed 28.4k times · Source

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)?

Answer

OpenSauce picture OpenSauce · May 21, 2011

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.