Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 936
soc Avatar asked May 21 '11 21:05

soc


People also ask

How do you check if a path is a file in Java?

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.

How do you check whether a file already exists in Java?

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.

Which method is used to check invoking object is file or not?

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.

How do you compare paths in Java?

Two file paths can be compared lexicographically in Java using the method java. io. File. compareTo().


2 Answers

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.

like image 86
OpenSauce Avatar answered Sep 28 '22 17:09

OpenSauce


look in the utility class Files for the package:

Files.exists(Path path,LinkOption... options) 
like image 34
ratchet freak Avatar answered Sep 28 '22 17:09

ratchet freak