Einstein
Einstein

Reputation: 370

Android: Check if file exist and if not create new one

I tried to check if a file exist on my android and if not my program should create a new one. But it always overwrites my existing file and is not checking if the files exist. Here is the code for the file checking part:

File urltest = new File(Environment.getExternalStorageDirectory()+ "/pwconfig/url.txt");
// check if file exists
if(urltest.exists());
else{       
// create an new file

File urlconfig = new File(myDir, "url.txt");
}

I really dont know why this is not working. It would be great if someone could help me.

Upvotes: 2

Views: 8470

Answers (2)

Vamshi
Vamshi

Reputation: 1495

Try this:

File sdDir = android.os.Environment.getExternalStorageDirectory();      
File dir = new File(sdDir,"/pwconfig/url.txt");

if (!dir.exists()) {
    dir.mkdirs();
}

Upvotes: 1

Simon
Simon

Reputation: 14472

You have a "rogue" semicolon

if(urltest.exists());

Instead:

if(urltest.exists()){
    // do something
}
else{       
    // create an new file
    File urlconfig = new File(myDir, "url.txt");
}

If you don't want to do something specific, you could rework it as:

if(!urltest.exists()){      
    // create an new file
    File urlconfig = new File(myDir, "url.txt");
}

Be careful with declaring variables inside control blocks. Remember that their scope is the control block itself. You might want this:

File urlconfig;
if(!urltest.exists()){      
    // create an new file
    urlconfig = new File(myDir, "url.txt");
}

Upvotes: 7

Related Questions