JAVA Check To See If A File Already Exists

How to check if a file already exists.

String file = “c:/file.csv”;

File f = new File(file);
if(f.exists()){
// code if file exists
}else{
// code if file doesn’t esist
}

The following example checks to see if the file exists, then asks the user if they want to overwrite it.
If the users selects yes, then the original file is deleted.

String file = “c:/file.csv”;

File f = new File(file);
if(f.exists()){

Object[] options = {“Yes”,
“No”,
“Cancel”};
int n = JOptionPane.showOptionDialog(null,
“File aready exists.\n”
+”Overwrite existing file?”,
“Warning”,
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[2]);

if(n == 0){
try{
f.delete();
}catch(Exception e){
JOptionPane.showMessageDialog(null, “Error deleting file.\nClose the file if it is open.”);
return;
}
}
else{
return;
}

}

// Code to write out to the file, now the original has been deleted.




Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s