2

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.

karllindmark
  • 6,031
  • 1
  • 26
  • 41
Laser42
  • 646
  • 2
  • 7
  • 24
  • Theoretically another process could have removed the file between `file.exists()` and construction of output stream. Generally you're forced to catch checked IO-based exceptions and somehow handle possible errors — e.g. show a message box with diagnostics and 'Retry' / 'Exit' buttons. – 9000 Jun 25 '11 at 08:22

2 Answers2

4

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
Sheharyar
  • 73,588
  • 21
  • 168
  • 215
  • 5
    Absolutely agree. HOWEVER, we've encountered some devices whose manufacturers will override getExternalStorageDirectory to point to Local storage, and not the SD card (which is infuriating). Just an FYI. – Adam Feb 06 '13 at 22:02
1

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

Ujwal Parker
  • 682
  • 7
  • 11
  • Ok, thank you all. I've considered to read/write data from internal memory and in future maybe I'll make export to sd option :) – Laser42 Jul 06 '11 at 19:04