3

This is my first Android app and my first attempt at writing something to file. I'm trying to capture a log according to these instructions and I'm getting the FileNotFoundExeption ENOENT (No such file or directory). That's fair enough because the directory does not exist. But then how do I create the directory? Or use another one? I don't know best practices for where to write logs to email them, nor do I know how to make a new directory for them.

This is the path I'm trying to use.

String path = Environment.getExternalStorageDirectory() + "/" + "MyFirstApp/";
      String fullName = path + "mylog";
File file = new File (fullName);
NSouth
  • 5,067
  • 7
  • 48
  • 83

2 Answers2

12

The parent dir doesn't exist yet, you must create the parent first before creating the file

String path = Environment.getExternalStorageDirectory() + "/" + "MyFirstApp/";
// Create the parent path
File dir = new File(path);
if (!dir.exists()) {
    dir.mkdirs();
}

String fullName = path + "mylog";
File file = new File (fullName);

Edit:

Thanks to Jonathans answer, this code sample is more correct. It uses the exists() method.

You also need the permission in your manifest:

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>
Francesco verheye
  • 1,574
  • 2
  • 14
  • 32
5

I'd like to add to Francesco's answer, that instead of asking if it's a directory, you could ask if it exists with dir.exists() method.

And also check that you've set the proper permissions in the Manifest file.

Hope it helps

Jonatan