Firstly, here's the code:

if(new File("ATM.xls").exists()){
    System.out.println("File exists");
    File excel = new File("ATM.xls");

What I'm trying to do is check whether or not a file exists and then create said file, if it does not exist. This all works fine, but somehow, I'm unable to use this created file in any way outside my IF statement. I'm trying to do the following:

WritableWorkbook wb = Workbook.createWorkbook(excel);

It's not working, and I'm not sure why. Any ideas??

Thanks for all help in advance :)

Hi Peter,

Thanks for replying.

I should have probably been a little clearer. I already have that and it was all working well, before I added the IF statement to check for the file's existence.


Here's a screenshot of the problem I have, if that helps at all to explain it.

Thanks again!

Ahhh, OK. Simple, lets examine code (sorry for cheeky comments)

if(new File("ATM.xls").exists()){ //check if file exists
    System.out.println("File exists"); //YES it does exist
    //but I failed to assigned to some object
    File excel = new File("ATM.xls");//doesn't exist so I create new file
    //but this go no further because it is local variable

So the code should be something like

File excel = new File("ATM.xls");
if(!excel.exists()) {
    try {
    } catch(IOException e) {
        Systemout.println("Failed to create new file, \n" + e.getMessage()); //Log framework would be much better instead of system print outs
//I have made sure file either exists or is created and now I can continue

When you declare a variable its scope is from the immediately preceeding { to the immediately following }. So your excel variable is in scope from line 211 to 213 only. Outside that scope the variable cannot be used. You have to declare variables somewhere where their scope includes all the places where you want to use them (just looking at your code fragment, anywhere that's NOT in the if or else blocks would work).

ps: The approach you have taken is not certain - in particular the exists test followed by create new file is not an atomic operation.
You are on much safer grounds using the modern Files class and its createFile method https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#createFile-java.nio.file.Path-java.nio.file.attribute.FileAttribute...-

Edit: following Peter's note... the nio package (including Files) was always a standard part of Java SE 7, it's just that it wasn't pushed very hard until later.

commented: Java 8, uhhhh, ohhhh.... Can't do it yet on Android ;-) +16

Worked like a dream Peter.

Thanks a lot!

Also, thanks for the further clarification, James.