Android Internal Storage — Complete Guide
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.filesDirfor persistent app-private files. - Use
context.cacheDirfor temporary files. - Use
context.getDir(name, MODE_PRIVATE)for named subdirectories. - Clean up
cacheDirperiodically. - Never use deprecated
Environment.getExternalStorageDirectory().
Common Mistakes with storage internal
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro