file.exists() and file.createNewFile() not working properly?

file-io, java

Solution

Hmm I'm sure not the problem but doing this is more readable:

File f = new File(filePathString);
if(!f.exists()) { /* do something */ }

rather then:

if(f1.exists() == false)
    {
      ...
    }

also when deleting a file always check its return value:

if(f.delete()) {//deleted successfully
}else {//couldnt delete
   //show error message
}

and as PeterLawrey said you should do the same for `createNewFile()`:

if(f.createNewFile()) {//created successfully
}else {//couldnt create
   //show error message
}

and lastly always check for permissions before trying to do anything:

if(f.canRead()&&f.canWrite()) {//can read and write free to do what is needed
   //do stuff
}else {
}

Problem

Basicly, lets say I got `File f1 = new File("C:\\somedir\\batch1.bat");` and `File f2 = new File("C:\\somedir\\batch2.bat");` and I have 2 ifs ``` if(f1.exists() == false) { showMessage("File 1 not detected, creating new..."); f1.createNewFile(); } else { showMessage("File 1 detected, deleting it and creating new..."); f1.delete(); f1.createNewFile(); } ``` and ``` if(f2.exists() == false) { showMessage("File 2 not detected, creating new..."); f2.createNewFile(); } else { showMessage("File 2 detected, deleting it and creating new..."); f2.delete(); f2.createNewFile(); } ``` First if executes "else" code no matter if file exists or not, and second one executes "if" part, without creating new file. help please! EDIT My `showMessage(String msg)` method does `System.out.println(msg)` just so you know.

Original source