Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Beginner
Jun 30, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Check if file exists

Is there a way for me to check if a file exists before writing to the file using Java?

You can determine if a file exists by calling the exists() method in the java.io.File class. A File instance represents a file on your local file system and allows you to perform operations on a file such as rename or delete. The exists() method will return true if a file exists, and false if it does not. However, if a file is contained in a directory in which you do not have read permission, exists() will return false even if the file exists. In addition, if you want to write to a file that you know exists, you can test if it is writable by invoking canWrite(). The following example program shows how to use the File class to determine if a file exists and is writable. It takes a list of files as command line arguments and for each file it prints out if the file exists as well as whether or not it is writable.

import java.io.*;

public final class FileExists {

  public static final void main(String args[]) {
    int filename;

    if(args.length < 1) {
      System.err.println("Usage: FileExists filename1 filename2 ...");

    for(filename = 0; filename < args.length; filename++) {
      File file;

      file = new File(args[filename]);

      if(file.exists()) {
	System.out.print(args[filename] + " exists and is ");
	  System.out.println("not writable.");
      } else
	System.out.println(args[filename] + " does not exist.");

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date