简体   繁体   中英

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.

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");
}

Try this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM