File Management
Storage Locations
Section titled “Storage Locations”External Root application file directory
Section titled “External Root application file directory”/storage/emulated/0/Android/data/your.package.name/files/
- Big File (No Limited Space & Required permission)
context.getExternalFilesDir(null) // use this to access External dirInternal Root application file directory
Section titled “Internal Root application file directory”/data/user/0/your.package.name/files/
- Small File (Limited Space & No permission require)
context.filesDir // use this to access Internal dirUse the Device Explorer in Android Studio to review/edit all files inside the Android emulator
Folder Operations
Section titled “Folder Operations”Get root dir path
Section titled “Get root dir path”null means get the root dir path
context.getExternalFilesDir(null)Get public view asset folders (e.g., Download Folder)
Section titled “Get public view asset folders (e.g., Download Folder)”Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)File/Folder Operations
Section titled “File/Folder Operations”Check if file exists
Section titled “Check if file exists”var myFile = File(context.getExternalFilesDir(null), "ocean.mp3")myFile.exists()Create a folder under root dir
Section titled “Create a folder under root dir”val customDir = File(context.getExternalFilesDir(null), "customFolder")
if (!customDir.exists()) { customDir.mkdir()}Get all files (via list)
Section titled “Get all files (via list)”fun getFiles(context: Context): List<File> { val dir = context.getExternalFilesDir(null) return dir?.listFiles()?.toList() ?: emptyList()}Write a file with FileWriter
Section titled “Write a file with FileWriter”withContext(Dispatchers.IO) { val file = File(context.getExternalFilesDir(null), "hello.json") FileWriter(file).use { writer -> writer.write(Gson().toJson(api)) }}Write with File OutputStream
Section titled “Write with File OutputStream”File(context.getExternalFilesDir(null), "customFolder") .outputStream().use { output -> <Your-InputStream>.copyTo(output)}Rename/Move file
Section titled “Rename/Move file”val oldFile = File(context.getExternalFilesDir(null), "ocean.mp3")val newFile = File(context.getExternalFilesDir(null), "new_ocean.mp3")
oldFile.renameTo(newFile)Delete a file
Section titled “Delete a file”File(context.getExternalFilesDir(null), "customFolder").delete()Get URI
Section titled “Get URI”File(context.getExternalFilesDir(null), "ocean.mp3").toUri()