Android Data Storage: SharedPreferences and File I/O Operations

SharedPreferences for Key-Value Storage

SharedPreferences provides a lightweight mechanism for storing primitive data types in XML format using a key-value pair structure. It is ideal for saving user preferences, session data, and small configuration settings.

Initialization and Configuration

To use SharedPreferences, obtain an instance through the Context and create an Editor for modifications:

public class PreferenceManager {
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    public PreferenceManager(Context context) {
        // MODE_PRIVATE ensures data is accessible only within this app
        preferences = context.getSharedPreferences("user_config", Context.MODE_PRIVATE);
        editor = preferences.edit();
    }
}

The operating mode parameter controls access levels:

  • MODE_PRIVATE: Default mode, restricts access to the calling application.
  • MODE_APPEND: Appends new data to existing file content rather than overwriting.
  • MODE_WORLD_READABLE/WRITEABLE: Deprecated due to security vulnerabilities.

Writing and Persisting Data

Data changes require explicit commitment. Two methods exist for saving changes:

public void saveUserData(String username, int age) {
    editor.putString("user_name", username);
    editor.putInt("user_age", age);
    editor.putBoolean("is_logged_in", true);
    
    // Synchronous commit - returns success/failure status
    boolean success = editor.commit();
    
    // Asynchronous apply - writes to memory first, then disk
    editor.apply();
}

commit() blocks the thread until the write completes and returns a boolean result. apply() writes to RAM immediately and persists to storage asynchronously, offering better performance for UI threads.

Reading Stored Values

Retrieve values using getter methods with default fallback values:

public String getUserName() {
    return preferences.getString("user_name", "");
}

public int getUserAge() {
    return preferences.getInt("user_age", 0);
}

Files are stored at: /data/data/<application_id>/shared_prefs/

File Storage Operations

For larger data sets or complex structures, Java I/O streams provide direct file manipulation capabilities within Android's storage hierarchy.

Internal Storage

Internal storage is private to the application and resides in the device's protected memory area.

public class InternalFileHandler {
    private static final String FILENAME = "app_data.txt";
    private Context context;

    public InternalFileHandler(Context ctx) {
        this.context = ctx;
    }

    public void writeContent(String data) {
        try (FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE)) {
            fos.write(data.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            Log.e("FileHandler", "Write failed", e);
        }
    }

    public String readContent() {
        StringBuilder builder = new StringBuilder();
        try (FileInputStream fis = context.openFileInput(FILENAME)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                builder.append(new String(buffer, 0, bytesRead, StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            Log.e("FileHandler", "Read failed", e);
        }
        return builder.toString();
    }
}

External Storage

External storage refers to shared storage spaces accessible to users and other applications. Modern Android versions require scoped storage access through specific APIs.

public class ExternalFileHandler {
    private Context context;

    public ExternalFileHandler(Context ctx) {
        this.context = ctx;
    }

    public void saveToExternal(String content, String filename) {
        File appDir = new File(context.getExternalFilesDir(null), "documents");
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        
        File targetFile = new File(appDir, filename);
        try (FileOutputStream fos = new FileOutputStream(targetFile)) {
            fos.write(content.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            Log.e("ExternalFile", "Save failed", e);
        }
    }

    public String loadFromExternal(String filename) {
        File appDir = new File(context.getExternalFilesDir(null), "documents");
        File targetFile = new File(appDir, filename);
        
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(targetFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            Log.e("ExternalFile", "Load failed", e);
        }
        return content.toString();
    }
}

getExternalFilesDir() provides app-specific external storage that does not require runtime permissions on newer Android versions. This directory is automatically cleaned up when the application is uninstalled.

Tags: Android sharedpreferences File Storage data persistence Java IO

Posted on Mon, 06 Jul 2026 17:11:44 +0000 by asaschool