Laser42
Laser42

Reputation: 744

Android how to check if file exist and else create one?

I have following question. I'd like to place a file named data.xml into sdcard/appname folder and use it for read and write application data.

So, when my main activity creates I need to check if this file exist:

public class appname extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(R.layout.no_elements_l);

      File file = getBaseContext().getFileStreamPath("/sdcard/appname/data.xml");
      if(file.exists()) { 

            return;

      } else {

            // create a File object for the parent directory
            File MTdirectory = new File("/sdcard/appname/");

            // have the object build the directory structure, if needed.
            MTdirectory.mkdirs();

            // create a File object for the output file
            File outputFile = new File(MTdirectory, "data.xml");

            // now attach the OutputStream to the file object, instead of a String representation
            FileOutputStream DataFile = new FileOutputStream(outputFile);
      }

But I have Unhandled exception type FileNotFoundException in last line. What's the problem? Uses permission WRITE_EXTERNAL_STORAGE is added to manifest.

Upvotes: 2

Views: 27425

Answers (2)

Sheharyar
Sheharyar

Reputation: 75750

Don't hardcode SDCard file path. It can be different for different devices and APIs.

For example it's /mnt/sdcard/ for Froyo while that of my Galaxy Nexus (JellyBean) is /storage/sdcard0/

Android Developer's Guide recommends using Environment.getExternalStorageDirectory()

Try doing it like this:

// Some Code

String path = Environment.getExternalStorageDirectory().getPath() + "/appname/";
File file = getBaseContext().getFileStreamPath(path);

// More Code

Upvotes: 4

Ujwal Parker
Ujwal Parker

Reputation: 682

Does the path '/sdcard/appname' exist? You check for the file before you check for the sub-directory 'appname'. You need to check if that exists before you try to access a file inside it.

Also if you simply need the file to read-write application data why not just go with internal storage - one less manifest permission :) -> read here for internal storage

Upvotes: 1

Related Questions