Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android write text file to internal storage

Tags:

java

android

Using emulator I am able to write a text file to /data/local but when I use my device, for the same path /data/local I get Permission denied. Could anyone tell me which path of Internal Storage is read-write and I can write my file there. It would be better if I could achieve this without rooting my device.

like image 595
FAZ Avatar asked Dec 27 '25 16:12

FAZ


2 Answers

Take a look at this guide from the Android docs.

Calling getFilesDir will return a File object for your app's internal directory.

You can use that to write a new file in the directory like this

File file = new File(context.getFilesDir(), fileName);

Here's an answer with an example of how to write text to a file using getFilesDir: https://stackoverflow.com/a/9306962/2278598

Or, you can use openFileOutput, like this

String fileName = "yourFileName";
String textToWrite = "This is some text!";
FileOutputStream outputStream;

try {
  outputStream = openFileOutput(fileName , Context.MODE_PRIVATE);
  outputStream.write(textToWrite.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}
like image 70
Andrew Brooke Avatar answered Dec 30 '25 05:12

Andrew Brooke


Android apps are isolated one to another, so your app has a dedicated folder in internal storage to read/write into it.

You can access it via

File path = Environment.getDataDirectory();

As it vary between devices.

Outside the app (e.g. from a shell, or a file explorer) you can't even read private data folders of the apps, you need a rooted device (as the emulator) to do it. If you want a file to be world-readable, put it in the external storage.

like image 41
webo80 Avatar answered Dec 30 '25 05:12

webo80



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!