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.
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/
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");
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 .
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.