Search code examples
androidandroid-file

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

Solution

  • 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>