Android读写文本、图片等

Kotlin方法

readText  : 读取文本形式的文件内容。
readLines : 按行读取文件内容。返回一个字符串的List,文件有多少行,队列中就有多少个元素。
readBytes : 读取字节数组形式的文件内容

1. 文本

val text = File("s").writeText()

val text = File("s").readText()

2. 图片

(1) 利用字节数组读取位图

val bytes = File(file_path).readBytes()
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)

(2) 利用输入流读取位图

val fis = File(file_path).inputStream()
val bitmap = BitmapFactory.decodeStream(fis)
fis.close()

(3) 直接从文件路径获取位图

val bitmap = BitmapFactory.decodeFile(file_path)

3. 指定扩展名的文件

val fileTree: FileTreeWalk = File(mPath).walk()
fileTree.maxDepth(1) //需遍历的目录层级为1,即无需检查子目录
        .filter { it.isFile } //只挑选文件,不处理文件夹
        .filter { it.extension in listOf("png", "jpg") } //选择扩展名为png和jpg的图片文件
        .forEach { //TODO 处理筛选出来的文件it  } //循环处理符合条件的文件
    }

猜你喜欢

转载自blog.csdn.net/riqthen/article/details/84983628