Data Storage with Native Android File System
Table of Contents
Some functionality may not need advanced and complicated features like Room, SQLite. And it turns out that we can simply use native Android file system, e.g., storing notes.
1. Native Android File System
The most important thing is that, how can we locate the private directory belonging to the package. The answer is easy, we can simply call the getFilesDir() method of the android.content.Context object.
import android.content.Context;
Context context;
context.getFilesDir();
Then, we can interact with files through Java’s java.io.File API.
import java.io.File;
/// create a file handler
File file = new File(context.getFilesDir(), "1.md");
/// Example 1. write to file
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
writer.write(/* some content */);
/// Example 2. Read from file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
// sb.toString();
/// Example 3. delete a file
file.delete();