-
Notifications
You must be signed in to change notification settings - Fork 12
Reading and writing files on Internal storage
rutura edited this page Apr 17, 2017
·
1 revision
- Three locations where you can work with files:
- Internal storage
- External storage
- Assets
- For internal storage, android lets you call:
FileOutputStream mOutput = Context.openFileOutput(FILENAME, Activity.MODE_PRIVATE);
to get a tream ou use to write to a file named FILENAME under the root of the app private internal storage space,and
FileInputStream mInput = Context.openFileInput(FILENAME);
to get a stream you use to read from that same file
- The second parameter to Context.openFileOutput() can either be MODE_PRIVATE : to override the file if it already is there or MODE_APPEND : to append the new content to the file if it already exists.
- The rest would be normal java I/O stuff.One possible way to write is :
try {
FileOutputStream mOutput = openFileOutput(FILENAME, Activity.MODE_PRIVATE);
String data = "THIS DATA WRITTEN TO A FILE";
mOutput.write(data.getBytes());
mOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
and you would possibly read like this:
try {
FileInputStream mInput = openFileInput(FILENAME);
byte[] data = new byte[128];
mInput.read(data);
mInput.close();
String display = new String(data);
tv.setText(display.trim());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}