Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOException: No Such File or Directory (Android)

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);
like image 847
NSouth Avatar asked Mar 01 '26 03:03

NSouth


2 Answers

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>
like image 56
Francesco verheye Avatar answered Mar 02 '26 15:03

Francesco verheye


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

like image 21
Jonatan Collard Bovy Avatar answered Mar 02 '26 17:03

Jonatan Collard Bovy