Search code examples
androidiostorage

android - save file to internal storage


I know this is a double post but the other threads didn't answer my question. I want to write a file to the directory of my app inside the Android directory in the internal storage

I added the permission to the manifest:

Manifest.xml Code:

 <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

and Java code:

 File myPath = new File(getFilesDir(), "test.dat");            
    myPath.mkdirs();
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        fos.write(bytes);
    } catch (Exception e) {

    }

however the directory for my app is not created and I cannot find the filename via search.

EDIT: there is actually a FileNotFoundException thrown, my bad. But I thought that mkdirs() would create all missing directories.


Solution

  • You can try with below:

    ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
    File directory = contextWrapper.getDir(getFilesDir().getName(), Context.MODE_PRIVATE);
    File file =  new File(directory,”fileName”);
    String data = “TEST DATA”;
    FileOutputStream fos = new FileOutputStream(“fileName”, true); // save
    fos.write(data.getBytes());
    fos.close();
    

    This will write the file in to the Device's internal storage at /data/user/0/com.yourapp/