Reputation: 1651
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.
Upvotes: 2
Views: 17970
Reputation: 1006704
however the directory for my app is not created and I cannot find the filename via search.
You, as a user, have no access to your app's portion of what the Android SDK refers to as internal storage, which is what you are using.
Users have access to what the Android SDK refers to as external storage.
Upvotes: 3
Reputation: 445
I cannot make comments, due to too low reputation, so I need to answer this way. I would slightly modify #AndroidDevUser answer, changing:
FileOutputStream fos = new FileOutputStream(“fileName”, true);
with
fos = new FileOutputStream(file, true);
Additionally I would add try / catch block.
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 = null; // save
try {
fos = new FileOutputStream(file, true);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 1
Reputation: 201
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/
Upvotes: 9
Reputation: 488
try this way
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/filename";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
// File file = new File(dir, "filename");
Upvotes: 5