devxlogo

Check if file exists

Check if file exists

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

Answer:
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 ...");      System.exit(1);    }    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 ");	if(file.canWrite())	  System.out.println("writable.");	else	  System.out.println("not writable.");      } else	System.out.println(args[filename] + " does not exist.");    }  }}
See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist