Skip to content

Android Internal Storage — Complete Guide

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Android Internal Storage. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

You save files to internal storage but they're visible in the file manager, or you use getFilesDir() and run out of space because you never clean up.

Wrong Approach ❌

// Using Environment.getExternalStorageDirectory() — deprecated!
val file = File(Environment.getExternalStorageDirectory(), "myapp/data.txt")
// Saving to internal storage without context
val file = File("data.txt") // Relative path — where does this go?

Output: Files saved in wrong location or inaccessible.

Right Approach ✅

class FileManager(private val context: Context) {

    // Internal storage — private to your app
    fun saveToInternalStorage(filename: String, content: String) {
        val file = File(context.filesDir, filename)
        file.writeText(content)
    }

    fun readFromInternalStorage(filename: String): String? {
        val file = File(context.filesDir, filename)
        return if (file.exists()) file.readText() else null
    }

    // Cache directory — system can delete these files
    fun saveToCache(filename: String, data: ByteArray) {
        val file = File(context.cacheDir, filename)
        file.writeBytes(data)
    }

    // Temporary file for sharing
    fun createTempFile(prefix: String, suffix: String): File {
        return File.createTempFile(prefix, suffix, context.cacheDir)
    }

    // File within a custom subdirectory
    fun saveToSubdirectory(subdir: String, filename: String, content: String) {
        val dir = File(context.filesDir, subdir)
        if (!dir.exists()) dir.mkdirs()
        File(dir, filename).writeText(content)
    }

    // List internal files
    fun listFiles(subdir: String = ""): List<String> {
        val dir = if (subdir.isEmpty()) context.filesDir
                  else File(context.filesDir, subdir)
        return dir.list()?.toList() ?: emptyList()
    }

    // Clean up old cache files
    fun cleanCache(maxAgeMs: Long = 7 * 24 * 60 * 60 * 1000L) { // 7 days
        context.cacheDir.listFiles()?.forEach { file ->
            if (System.currentTimeMillis() - file.lastModified() > maxAgeMs) {
                file.delete()
            }
        }
    }

    // Use internal storage for sensitive data
    // Note: internal storage is still accessible on rooted devices
    // For truly sensitive data, use EncryptedSharedPreferences or EncryptedFile

    // Check available space
    fun hasAvailableSpace(requiredBytes: Long): Boolean {
        val stat = StatFs(context.filesDir.path)
        val available = stat.availableBlocksLong * stat.blockSizeLong
        return available >= requiredBytes
    }
}

Output: Files stored correctly in app's private storage.

Prevention

  • Use context.filesDir for persistent app-private files.
  • Use context.cacheDir for temporary files.
  • Use context.getDir(name, MODE_PRIVATE) for named subdirectories.
  • Clean up cacheDir periodically.
  • Never use deprecated Environment.getExternalStorageDirectory().

Common Mistakes with storage internal

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between filesDir and cacheDir?

filesDir persists until the app is uninstalled. cacheDir can be cleared by the system when storage is low. Use cacheDir for temporary files, filesDir for user data.

### Are files in internal storage private?

Yes. Internal storage files are only accessible by your app (unless the device is rooted). Other apps cannot read them without root access.

### What happens to internal files when the app is uninstalled?

All files in filesDir and cacheDir are deleted when the app is uninstalled. Files in external storage (getExternalFilesDir()) are also removed.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro