简体   繁体   中英

How to Check if a File Exists in a Directory in Java

I would like to find out if a particular directory has a file in it already in Java, specifically I need to check if the file exists in a given directory using Java code.

However, I need the code to not crash and burn due to the various permissions / file rights and how it can be used. It's going in a cross platform app. I've seen the question checking if file exists in a specific directory this isn't what I'm needing however.

Any kind soles with some clean Java code ideas.. (sorry if my English is bad I'm not American).

Update: Found what I needed eventually https://javajudo.com/how-to-check-if-a-file-exists-in-a-directory-in-java/

Thanks, for the help.

You can test whether a file or directory exists using the Java File exists() method.

File file = new File("/temp.txt");
boolean cond1 = file.exists();

The method will return true when the file or directory is found and false if the file is not found.

You can also use the Files.exists() and Files.notExists() Java methods if that is easier too.

There are also the constants Constants.FILE_EXISTS and Constants.FILE_EXISTS you can use to test conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM