Teri Ga
Teri Ga

Reputation: 21

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.

Upvotes: 1

Views: 10437

Answers (2)

westman379
westman379

Reputation: 723

My solution:

boolean check_if_file_exists(String file_path)
{
    if (file_path != null)
    {
        File f = new File(file_path);
        if(f.exists() && !f.isDirectory()) {
            return true;
        }
    }
    return false;
}

Upvotes: 0

SameSize
SameSize

Reputation: 36

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.

Upvotes: 2

Related Questions