dcsimg
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

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


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.");

    }
  }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

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