KAHIBARO Bookshelves
Discord Login Register

14.2. Internal Storage

Understanding Internal Storage on Android

Internal storage is a private area on the device where your app can save files. Only your app can normally access these files. This makes internal storage the simplest and safest place to keep user data that should not be shared with other apps.

When the user uninstalls your app, the system removes your internal storage files automatically. You do not have to clean them up yourself in most cases.

Where Internal Storage Lives in an App

Every installed app gets its own internal files directory. In code, you usually access it using a Context object, which you have in activities, services, and many other places.

The most common directory is returned by filesDir. In Kotlin you can write something like:

val directory = filesDir
val path = directory.absolutePath

This directory is unique to your app. Other apps cannot read or write here without special permissions that normal apps do not get.

You can also get a cache directory using cacheDir. This is for temporary files that the system may delete when it needs space.

Creating and Writing Files in Internal Storage

To write a text file into internal storage, you usually open a file output stream and then write bytes or text. One of the simplest ways is to use openFileOutput, which automatically writes to your internal files directory.

fun saveTextToFile(fileName: String, text: String) {
    openFileOutput(fileName, MODE_PRIVATE).use { output ->
        output.write(text.toByteArray())
    }
}

This method creates the file if it does not exist, or replaces its contents if it does. The MODE_PRIVATE flag keeps the file private to your app.

You can also build a File manually if you want more control over paths.

val file = File(filesDir, "notes.txt")
file.writeText("Hello internal storage")

When you use these APIs, you do not need any storage permissions. Internal storage access is always allowed for your own app.

Internal storage writes do not require the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions. If you are only using internal storage, do not request external storage permissions.

Reading Files from Internal Storage

Reading is similar to writing. You open an input stream and then read the content.

If you used openFileOutput, you can use openFileInput to read the same file.

fun readTextFromFile(fileName: String): String {
    return openFileInput(fileName).bufferedReader().use { reader ->
        reader.readText()
    }
}

If you created a File object, you can use its read helpers.

val file = File(filesDir, "notes.txt")
val content = file.readText()

When you read a file, be prepared for the possibility that it does not exist yet. In that case the read methods can throw an exception.

Listing and Managing Internal Files

Sometimes you need to know what files exist in your internal directory. You can use fileList if you saved files using openFileOutput, or you can use listFiles on the directory File.

val names = fileList()
for (name in names) {
    println("Internal file: $name")
}

Or using the directory:

val files = filesDir.listFiles()
files?.forEach { file ->
    println("Path: ${file.absolutePath}")
}

To delete a file that you created with openFileOutput, you can call deleteFile.

val deleted = deleteFile("notes.txt")

If you created your file with File, you can remove it using:

val file = File(filesDir, "notes.txt")
val deleted = file.delete()

Use deletion carefully. Once removed, the file data cannot be recovered by your app.

Working with Cache in Internal Storage

Your app can also store temporary data in the internal cache directory returned by cacheDir. This is useful for images, downloaded content, or anything that you can recreate.

val tempFile = File.createTempFile(
    prefix = "image_",
    suffix = ".tmp",
    directory = cacheDir
)

The system may delete cache files to free space. You should never store important user data in the cache directory.

You can clear your own cache files if you know they are no longer needed.

fun clearInternalCache() {
    cacheDir.listFiles()?.forEach { file ->
        file.delete()
    }
}

File Modes and Access Flags

When you use openFileOutput, you pass a mode flag. The most common one is MODE_PRIVATE. This mode makes sure that the file is only visible to your app and that any previous content is replaced.

There are other modes in the API, but many older flags are now discouraged. In modern Android development, you typically use MODE_PRIVATE only and manage file content yourself.

Always use MODE_PRIVATE for internal storage files. Do not rely on other modes for sharing files. Use proper sharing APIs instead of weakening your internal file privacy.

Internal Storage and User Privacy

Internal storage is a good place for data that must stay inside your app. Examples are user configuration, cached authentication tokens, and small databases.

Even though other apps cannot directly read these files, your app should still avoid storing secrets in plain text if exposure would be critical. Devices can be rooted or physically accessed, which can bypass normal app sandboxing.

When you design your storage layer, treat internal storage as private to your app, but not as a complete security boundary against very determined attackers.

Handling Errors and Edge Cases

File operations can fail. The internal storage might be full, a file might not exist, or there could be I/O errors. It is important to handle failures so that your app does not crash.

You can catch exceptions around file operations.

fun safeRead(fileName: String): String? {
    return try {
        openFileInput(fileName).bufferedReader().use { it.readText() }
    } catch (e: FileNotFoundException) {
        null
    } catch (e: IOException) {
        null
    }
}

If you receive null, you can decide whether to show a default value, ask the user to try again, or recreate the file with default content.

Also consider the size of data. Very large files in internal storage may affect app performance and device storage. For large or long lived data, combine internal storage with other techniques like databases, which are covered in another chapter.

Choosing Internal Storage in Your App

When you decide where to store data, internal storage is often the first option you should consider. It requires no runtime permissions, it is easier to manage than external storage, and it respects user privacy.

Use internal storage for app specific files that only your app needs. Store them under filesDir for persistent data and under cacheDir for temporary data.

By following this pattern, you keep your data organized and your app simpler, while allowing the system to safely manage your files over the lifetime of your application.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Introduction to Android Development
    • ☰ 1.1. What is Android
      • ☰ 1.2. Android Ecosystem and Versions
        • ☰ 1.3. Native vs Cross-Platform Development
          • ☰ 1.4. Course Structure and Goals
          • ☰ 2. Setting Up the Development Environment
            • ☰ 2.1. Installing Android Studio
              • ☰ 2.2. Android SDK and Tools
                • ☰ 2.3. Emulator Setup
                  • ☰ 2.4. Running Apps on a Physical Device
                  • ☰ 3. Kotlin Basics for Android
                    • ☰ 3.1. Variables and Data Types
                      • ☰ 3.2. Control Flow (if, when, loops)
                        • ☰ 3.3. Functions
                          • ☰ 3.4. Null Safety
                            • ☰ 3.5. Packages and Imports
                            • ☰ 4. Object-Oriented Programming in Kotlin
                              • ☰ 4.1. Classes and Objects
                                • ☰ 4.2. Constructors
                                  • ☰ 4.3. Inheritance and Polymorphism
                                    • ☰ 4.4. Interfaces
                                      • ☰ 4.5. Data Classes and Enums
                                      • ☰ 5. Android Project Structure
                                        • ☰ 5.1. Android Studio Project Overview
                                          • ☰ 5.2. Gradle Build System
                                            • ☰ 5.3. AndroidManifest.xml
                                              • ☰ 5.4. Resource Directories
                                              • ☰ 6. Your First Android App
                                                • ☰ 6.1. Creating a New Project
                                                  • ☰ 6.2. Understanding MainActivity
                                                    • ☰ 6.3. Running and Debugging the App
                                                    • ☰ 7. Android App Lifecycle
                                                      • ☰ 7.1. Activity Lifecycle
                                                        • ☰ 7.2. Lifecycle Callbacks
                                                          • ☰ 7.3. Configuration Changes
                                                          • ☰ 8. Layouts and Views
                                                            • ☰ 8.1. XML Layout Basics
                                                              • ☰ 8.2. LinearLayout
                                                                • ☰ 8.3. ConstraintLayout
                                                                  • ☰ 8.4. View Attributes
                                                                    • ☰ 8.5. Responsive Layouts
                                                                    • ☰ 9. User Interaction
                                                                      • ☰ 9.1. Buttons and Click Listeners
                                                                        • ☰ 9.2. TextView and EditText
                                                                          • ☰ 9.3. Handling User Input
                                                                            • ☰ 9.4. Toasts and Snackbars
                                                                            • ☰ 10. Styling and Themes
                                                                              • ☰ 10.1. Colors and Dimensions
                                                                                • ☰ 10.2. Styles
                                                                                  • ☰ 10.3. Themes
                                                                                    • ☰ 10.4. Dark Mode Support
                                                                                    • ☰ 11. Navigation Between Screens
                                                                                      • ☰ 11.1. Intents
                                                                                        • ☰ 11.2. Passing Data Between Activities
                                                                                          • ☰ 11.3. Activity Back Stack
                                                                                          • ☰ 12. Fragments
                                                                                            • ☰ 12.1. Fragment Basics
                                                                                              • ☰ 12.2. Fragment Lifecycle
                                                                                                • ☰ 12.3. Fragment Transactions
                                                                                                  • ☰ 12.4. Fragment Communication
                                                                                                  • ☰ 13. RecyclerView and Lists
                                                                                                    • ☰ 13.1. RecyclerView Basics
                                                                                                      • ☰ 13.2. Adapters and ViewHolders
                                                                                                        • ☰ 13.3. Click Handling in Lists
                                                                                                        • ☰ 14. Data Storage Basics
                                                                                                          • ☰ 14.1. SharedPreferences
                                                                                                            • ☰ 14.2. Internal Storage
                                                                                                              • ☰ 14.3. File Handling
                                                                                                              • ☰ 15. Databases with Room
                                                                                                                • ☰ 15.1. SQLite Overview
                                                                                                                  • ☰ 15.2. Room Entities
                                                                                                                    • ☰ 15.3. Data Access Objects
                                                                                                                      • ☰ 15.4. Database Migrations
                                                                                                                      • ☰ 16. Working with Images and Media
                                                                                                                        • ☰ 16.1. ImageView and Drawable Resources
                                                                                                                          • ☰ 16.2. Loading Images from the Internet
                                                                                                                            • ☰ 16.3. Audio and Video Playback
                                                                                                                            • ☰ 17. Permissions and Security
                                                                                                                              • ☰ 17.1. App Permissions
                                                                                                                                • ☰ 17.2. Runtime Permissions
                                                                                                                                  • ☰ 17.3. Security Best Practices
                                                                                                                                  • ☰ 18. Networking Fundamentals
                                                                                                                                    • ☰ 18.1. HTTP Basics
                                                                                                                                      • ☰ 18.2. REST APIs
                                                                                                                                        • ☰ 18.3. JSON Parsing
                                                                                                                                        • ☰ 19. Networking with Retrofit
                                                                                                                                          • ☰ 19.1. Retrofit Setup
                                                                                                                                            • ☰ 19.2. API Interfaces
                                                                                                                                              • ☰ 19.3. Error Handling
                                                                                                                                              • ☰ 20. Background Tasks
                                                                                                                                                • ☰ 20.1. Threads and Handlers
                                                                                                                                                  • ☰ 20.2. Kotlin Coroutines
                                                                                                                                                    • ☰ 20.3. Lifecycle-Aware Tasks
                                                                                                                                                    • ☰ 21. Services and WorkManager
                                                                                                                                                      • ☰ 21.1. Services Overview
                                                                                                                                                        • ☰ 21.2. Foreground vs Background Services
                                                                                                                                                          • ☰ 21.3. WorkManager
                                                                                                                                                          • ☰ 22. Architecture Components
                                                                                                                                                            • ☰ 22.1. ViewModel
                                                                                                                                                              • ☰ 22.2. LiveData
                                                                                                                                                                • ☰ 22.3. MVVM Architecture
                                                                                                                                                                • ☰ 23. Dependency Injection
                                                                                                                                                                  • ☰ 23.1. Dependency Injection Concepts
                                                                                                                                                                    • ☰ 23.2. Hilt Basics
                                                                                                                                                                    • ☰ 24. Material Design
                                                                                                                                                                      • ☰ 24.1. Material Design Principles
                                                                                                                                                                        • ☰ 24.2. Material Components
                                                                                                                                                                          • ☰ 24.3. Adaptive UI Design
                                                                                                                                                                          • ☰ 25. Animations and Motion
                                                                                                                                                                            • ☰ 25.1. View Animations
                                                                                                                                                                              • ☰ 25.2. Property Animations
                                                                                                                                                                                • ☰ 25.3. Transitions
                                                                                                                                                                                • ☰ 26. Notifications
                                                                                                                                                                                  • ☰ 26.1. Notification Basics
                                                                                                                                                                                    • ☰ 26.2. Notification Channels
                                                                                                                                                                                      • ☰ 26.3. Action Buttons
                                                                                                                                                                                      • ☰ 27. Location and Sensors
                                                                                                                                                                                        • ☰ 27.1. Location Services
                                                                                                                                                                                          • ☰ 27.2. Using GPS
                                                                                                                                                                                            • ☰ 27.3. Device Sensors
                                                                                                                                                                                            • ☰ 28. Maps and Geolocation
                                                                                                                                                                                              • ☰ 28.1. Google Maps Integration
                                                                                                                                                                                                • ☰ 28.2. Markers and Map Events
                                                                                                                                                                                                • ☰ 29. Testing Android Apps
                                                                                                                                                                                                  • ☰ 29.1. Unit Testing
                                                                                                                                                                                                    • ☰ 29.2. UI Testing with Espresso
                                                                                                                                                                                                    • ☰ 30. Performance Optimization
                                                                                                                                                                                                      • ☰ 30.1. Memory Management
                                                                                                                                                                                                        • ☰ 30.2. Profiling Tools
                                                                                                                                                                                                          • ☰ 30.3. Performance Best Practices
                                                                                                                                                                                                          • ☰ 31. App Debugging
                                                                                                                                                                                                            • ☰ 31.1. Logcat
                                                                                                                                                                                                              • ☰ 31.2. Breakpoints
                                                                                                                                                                                                                • ☰ 31.3. Debugging Common Issues
                                                                                                                                                                                                                • ☰ 32. App Packaging and Signing
                                                                                                                                                                                                                  • ☰ 32.1. APK vs AAB
                                                                                                                                                                                                                    • ☰ 32.2. Signing Configurations
                                                                                                                                                                                                                      • ☰ 32.3. Release Builds
                                                                                                                                                                                                                      • ☰ 33. Publishing on Google Play
                                                                                                                                                                                                                        • ☰ 33.1. Google Play Console
                                                                                                                                                                                                                          • ☰ 33.2. Store Listing
                                                                                                                                                                                                                            • ☰ 33.3. Release Tracks
                                                                                                                                                                                                                            • ☰ 34. Monetization Strategies
                                                                                                                                                                                                                              • ☰ 34.1. Ads
                                                                                                                                                                                                                                • ☰ 34.2. In-App Purchases
                                                                                                                                                                                                                                  • ☰ 34.3. Subscriptions
                                                                                                                                                                                                                                  • ☰ 35. Advanced Topics
                                                                                                                                                                                                                                    • ☰ 35.1. Custom Views
                                                                                                                                                                                                                                      • ☰ 35.2. Introduction to Jetpack Compose
                                                                                                                                                                                                                                      • ☰ 36. Capstone Project
                                                                                                                                                                                                                                        • ☰ 36.1. Project Planning
                                                                                                                                                                                                                                          • ☰ 36.2. Implementation