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