Android开发中将String数据写入本地文件
·
在开发中,我们经常会遇到将字符串写入文件中,用来验证我们获取的字符串是否正确,下面我们用讲解一个简单的写入文件的方法:
首先,我们得先添加写入的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
下面是对应的写入代码:本篇主要是Kotlin写的:
@JvmStatic
fun writeTxtToFile(strcontent: String, filePath: String, fileName: String) {
// 将字符串写入到文本文件中
// fun writeTxtToFile(strcontent: String, filePath: String, fileName: String) {
//生成文件夹之后,再生成文件,不然会出错
makeFilePath1(filePath, fileName)
val strFilePath = filePath + fileName
// 每次写入时,都换行写
val strContent = """
$strcontent
""".trimIndent()
try {
val file = File(strFilePath)
if (!file.exists()) {
Log.d("TestFile", "Create the file:$strFilePath")
file.parentFile.mkdirs()
file.createNewFile()
}
val raf = RandomAccessFile(file, "rwd")
raf.seek(file.length())
raf.write(strContent.toByteArray())
raf.close()
} catch (e: java.lang.Exception) {
Log.e("TestFile", "Error on write File:$e")
}
}
//生成文件
fun makeFilePath1(filePath: String, fileName: String): File? {
var file: File? = null
makeRootDirectory1(filePath)
try {
file = File(filePath + fileName)
if (!file.exists()) {
file.createNewFile()
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
return file
}
//生成文件夹
fun makeRootDirectory1(filePath: String?) {
var file: File? = null
try {
file = File(filePath)
if (!file.exists()) {
file.mkdir()
}
} catch (e: java.lang.Exception) {
Log.i("error:", e.toString() + "")
}
}
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐


所有评论(0)