Explain Codes LogoExplain Codes Logo

Read/write String from/to a File in Android

java
file-management
android-development
exception-handling
Alex KataevbyAlex Kataev·Mar 4, 2025
TLDR

Read and write strings to a file in Android can be effectively done by using FileOutputStream to write and FileInputStream to read. The OutputStreamWriter and InputStreamReader allows proper character handling.

Write in just a few lines:

try (FileOutputStream fos = openFileOutput("example.txt", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fos)) { // You're doing great, keep going! osw.write("The content of your choosing"); }

Read with minimal code:

StringBuilder sb = new StringBuilder(); try (FileInputStream fis = openFileInput("example.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr)) { // Let's give each line of the file some love using a loop for (String line; (line = br.readLine()) != null; ) sb.append(line).append('\n'); } String content = sb.toString();

Don't forget to handle permissions, especially if you're targeting Android 6.0+.

Exception handling and resource management

In the world of data integrity and app stability, try-catch blocks prove handy for smoothly handling exceptions during read/write operations. Handling exceptions such as FileNotFoundException and IOException ensures your application remains stable.

Closing your streams after operations prevents resource leaks like a champ. In the code snippets above, we use try-with-resources which automatically closes resources after usage.

try { // ta-da! Your file read logic } catch (FileNotFoundException e) { // Oops, looks like our file pulled a Houdini! e.printStackTrace(); } catch (IOException e) { // Reading file turned into an Indiana Jones adventure! e.printStackTrace(); } finally { // All missions require a clean-up. }

Efficient file operations with internal storage

Save data privately to your app's internal storage using context.openFileOutput and context.openFileInput. Be mindful of file name and mode (MODE_PRIVATE, MODE_APPEND, etc.). OutputStreamWriter assists in properly encoding your characters, commonly to UTF-8.

File file = new File(context.getFilesDir(), "example.txt");

When reading files, sing the praise of efficiency. BufferedReader is a delightful tool that allows efficient reading of text files line by line.

Going pro with file operations

Sharpen your File class skills for seamless file operations. Utilize FileReader and FileWriter for object-oriented file read/write operations.

Boost performance by reading files in smaller chunks. Using inputStream.available() ensures file size is ascertained and buffer space is allocated accordingly. Always close InputStream to avoid memory leaks.

File("example.txt").writeText("The content of your choosing") val content = File("example.txt").readText()

Ensure to request the appropriate permissions when accessing external storage. Include these in your AndroidManifest.xml file and handle runtime permission requests for Android 6.0+.

Tuning performance and adopting best practices

Performance tuning is the cherry on top of file operations. Minimize the use of constants within your read/write logic. Instead, use buffered mechanisms and StringBuilder to give memory management and speed a high-five.

To avoid context-related memory leaks, ensure your context reference is appropriately scoped to the current operation.

For security, consider using encryption and decryption streams to add a vault door to your important data.

If your application targets various Android versions and devices, be aware of the changes in storage access rules with Android 10 (API level 29+) and the introduction of scoped storage.