DVK
DVK

Reputation: 129519

How do I check if a file exists in Java?

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's -e $filename)?

The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.

If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.

Upvotes: 1005

Views: 1514459

Answers (19)

3rdRockSoftware
3rdRockSoftware

Reputation: 85

I struggled for hours with this because the file is in a directory on a server that doesn't allow access from netbeans. Thus for reasons explained above .isFile(), .exists() etc don't work for me.

My workaround was this:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.nio.file.Path;

public class CSVReader
{
    private boolean fileExists = false;

    public void readCSVFile(Path path)
    {
        try
        {
            System.out.println("reading csv file");
            BufferedReader br = new BufferedReader(new fileReader(path.toString()));
            //netbeans complains that br is never read but doesn't stop anything working
            setFileExists(true);
        }
        catch (FileNotFoundException ex)
        {
            System.out.println("file does not seem to exist. New file will be created");
        }
    }
}

my csvWriter method then uses the boolean (fileExists) to create a new file and then either write the header as well as the values, or just append the values to the end of the file.

I am using openCSV and also setting the 'append' flag to true if the file already exists

import com.opencsv.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;

public class WriteToCSV
{
public void createCSVfile(Path path, boolean fileExists)
    {
        FileWriter outputFile = null;
        CSVWriter w = null;
        String[] data =
        {
            "col1 val", "col2 value", "col3 value", "col4 value"
        };
        try
        {
            File f = new File(path.toString());
            if (fileExists)
            {
                System.out.println("file exists");
                outputFile = new FileWriter(f, true); //append flag set
                w = new CSVWriter(outputFile);
            }
            else
            {
                System.out.println("file doesn't exist");
                outputFile = new FileWriter(f); //append flag not set. Data will be overwritten
                w = new CSVWriter(outputFile);
                w.writeNext(COLUMN_HEADERS);
            }
            w.writeNext(data);
            w.close();
            System.out.println("file created at " + path);
        }
        catch (IOException ex)
        {
            System.out.println("unable to create new file " + path.getFileName() + ". " + ex);
            System.exit(Thread.currentThread().getStackTrace()[1].getLineNumber());
        }
        finally
        {
            try
            {
                outputFile.close();
            }
            catch (IOException ex)
            {
                System.out.println("unable to close csv file " + ex);
                System.exit(Thread.currentThread().getStackTrace()[1].getLineNumber());
            }
        }
    }
}

Upvotes: 0

Shapur
Shapur

Reputation: 577

If spring framework is used and the file path starts with classpath:

public static boolean fileExists(String sFileName) {
    if (sFileName.startsWith("classpath:")) {
        String path = sFileName.substring("classpath:".length());
        ClassLoader cl = ClassUtils.getDefaultClassLoader();
        URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
        return (url != null);
    } else {
        Path path = Paths.get(sFileName);
        return Files.exists(path);
    }
}

Upvotes: 0

user10525734
user10525734

Reputation:

You must use the file class , create a file instance with the path of the file you want to check if existent . After that you must make sure that it is a file and not a directory . Afterwards you can call exist method on that file object referancing your file . Be aware that , file class in java is not representing a file . It actually represents a directory path or a file path , and the abstract path it represents does not have to exist physically on your computer . It is just a representation , that`s why , you can enter a path of a file as an argument while creating file object , and then check if that folder in that path does really exist , with the exists() method .

Upvotes: 0

Wonil
Wonil

Reputation: 6727

By using nio in Java SE 7,

import java.nio.file.*;

Path path = Paths.get(filePathString);

if (Files.exists(path)) {
  // file exist
}

if (Files.notExists(path)) {
  // file is not exist
}

If both exists and notExists return false, the existence of the file cannot be verified. (maybe no access right to this path)

You can check if path is a directory or regular file.

if (Files.isDirectory(path)) {
  // path is directory
}

if (Files.isRegularFile(path)) {
  // path is regular file
}

Please check this Java SE 7 tutorial.

Upvotes: 225

Atul Jain
Atul Jain

Reputation: 1085

There is specific purpose to design these methods. We can't say use anyone to check file exist or not.

  1. isFile(): Tests whether the file denoted by this abstract pathname is a normal file.
  2. exists(): Tests whether the file or directory denoted by this abstract pathname exists. docs.oracle.com

Upvotes: 0

Amandeep Singh
Amandeep Singh

Reputation: 3840

Simple example with good coding practices and covering all cases :

 private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
        File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
        if (f.exists()) {
            throw new FileAlreadyExistsException(f.getAbsolutePath());
        } else {
            try {
                URL u = new URL(url);
                FileUtils.copyURLToFile(u, f);
            } catch (MalformedURLException ex) {
                Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

Reference and more examples at

https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations

Upvotes: 1

Rodrigo Pavan
Rodrigo Pavan

Reputation: 1

You can make it this way

import java.nio.file.Paths;

String file = "myfile.sss";
if(Paths.get(file).toFile().isFile()){
    //...do somethinh
}

Upvotes: 0

Sean A.O. Harney
Sean A.O. Harney

Reputation: 24507

Using java.io.File:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
}

Upvotes: 1540

Raghu K Nair
Raghu K Nair

Reputation: 3942

There are multiple ways to achieve this.

  1. In case of just for existence. It could be file or a directory.

    new File("/path/to/file").exists();
    
  2. Check for file

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isFile()) {}
    
  3. Check for Directory.

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isDirectory()) {}
    
  4. Java 7 way.

    Path path = Paths.get("/path/to/file");
    Files.exists(path)  // Existence 
    Files.isDirectory(path)  // is Directory
    Files.isRegularFile(path)  // Regular file 
    Files.isSymbolicLink(path)  // Symbolic Link
    

Upvotes: 21

avi.elkharrat
avi.elkharrat

Reputation: 6810

I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.

The following snippet

if(Files.isRegularFile(Paths.get(pathToFile))) {
    // do something
}

is perfectly satifactory, because method isRegularFile returns false if file does not exist. Therefore, no need to check if Files.exists(...).

Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.

From Java Oracle documentation

Upvotes: 7

iviorel
iviorel

Reputation: 312

Don't use File constructor with String.
This may not work!
Instead of this use URI:

File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) { 
    // to do
}

Upvotes: 1

Wendel
Wendel

Reputation: 2977

Using Java 8:

if(Files.exists(Paths.get(filePathString))) { 
    // do something
}

Upvotes: 58

X-Fate
X-Fate

Reputation: 323

For me a combination of the accepted answer by Sean A.O. Harney and the resulting comment by Cort3z seems to be the best solution.

Used the following snippet:

File f = new File(filePathString);
if(f.exists() && f.isFile()) {
    //do something ...
}

Hope this could help someone.

Upvotes: 9

just somebody
just somebody

Reputation: 19257

first hit for "java file exists" on google:

import java.io.*;

public class FileTest {
    public static void main(String args[]) {
        File f = new File(args[0]);
        System.out.println(f + (f.exists()? " is found " : " is missing "));
    }
}

Upvotes: 15

Francis Upton IV
Francis Upton IV

Reputation: 19443

You can use the following: File.exists()

Upvotes: 15

user207421
user207421

Reputation: 311023

Don't. Just catch the FileNotFoundException. The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:

  • double the code
  • the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
  • the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.

Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.

Upvotes: 15

rizwan
rizwan

Reputation: 521

File f = new File(filePathString); 

This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:

f.createNewFile();

So f.exists() can be used to check whether such a file exists or not.

Upvotes: 34

Chris Dail
Chris Dail

Reputation: 26049

I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

new File("path/to/file.txt").isFile();

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

Upvotes: 486

jhumble
jhumble

Reputation: 555

f.isFile() && f.canRead()

Upvotes: 28

Related Questions