一、文件路径
SD卡根目录:
Environment.getExternalStorageDirectory()
absolutePath: /storage/emulated/0
外部存储应用空间:
context.getExternalFilesDir(Environment.DIRECTORY_DCIM):
absolutePath: /storage/emulated/0/Android/data/com.example.test/files/DCIM
getExternalFilesDir(Environment.DIRECTORY_MUSIC):
absolutePath: /storage/emulated/0/Android/data/com.example.test/files/Music
context.externalCacheDir:
absolutePath: /storage/emulated/0/Android/data/com.example.test/cache
内部存储应用空间:
context.filesDir:
absolutePath: /data/user/0/com.example.test/files
context.cacheDir:
absolutePath: /data/user/0/com.example.test/cache
创建文件的方式:
File.createTempFile("data", ".txt", getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS))
absolutePath: /storage/emulated/0/Android/data/com.example.test/files/Documents/data5258187288438298744.txt
File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "data.txt")
absolutePath: /storage/emulated/0/Android/data/com.example.test/files/Documents/data.txt
1、应用删除,外部存储和内部存储包(../com.example.test/)下面的文件都会被删
2、files目录下,一般放一些长时间保存的数据,设置-应用-应用详情-清除数据 会清除files目录
3、cache目录下,一般存放临时缓存数据,设置-应用-应用详情-清除缓存 会清除files目录
4、通过context 获取的路径不需要权限申请,包括 context.getExternalFilesDir()
5、file.delete()
立即直接删除,file.deleteOnExit()
并非立即删除,是在虚拟机正常运行结束后才会删除。
二、常用方法
//是否存在sd卡
fun isExistSDCard() =
Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
//写文件并返回filePath
fun writeFile1(context: Context, fileName: String, content: String): String {
return File(
context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS),
fileName
).apply {
FileOutputStream(this).use { outputStream ->
outputStream.write(content.toByteArray())
outputStream.flush()
}
}.absolutePath
}
//写文件并返回filePath,kotlin扩展方法
fun writeFile2(context: Context, fileName: String, content: String): String {
return File(
context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS),
fileName
).apply {
this.writeText(content)
}.absolutePath
}
//追加写入,kotlin扩展方法
fun appendFile(context: Context, filePath: String, content: String) {
File(filePath).appendText(content, StandardCharsets.UTF_8)
}
//读文件
fun readFile1(filePath: String): String {
return StringBuffer().apply {
File(filePath)
.readLines(StandardCharsets.UTF_8)
.forEach {
this.append(it).append("\n")
}
}.toString()
}
//读文件,kotlin扩展方法
fun readFile2(filePath: String): String {
return File(filePath).readText()
}
//存图片
fun writeBitmap(context: Context, bitmap: Bitmap, fileName: String): String {
return File(
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
fileName
).apply {
FileOutputStream(this).use { outputStream ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
outputStream.flush()
}
}.absolutePath
}
持续更新中...