zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Android 动态修改 html 文件的字符串

Android文件HTML 字符串 修改 动态
2023-09-27 14:28:04 时间

有时候,需要动态修改 html 文件的字符串,如多语言,或者一些老版本的兼容。

思路比较简单,就是把 html 的字符串读出来,替换某个字符串就好了。
需要注意的时候,在读的时候,需要保留 html 的换行br,避免格式不对的问题,简单的代码如下:

    private fun replaceHtmlMsg(htmlFile: File) {
            val fr = FileReader(htmlFile)
            val br = BufferedReader(fr)
            val sb = StringBuffer()
            var eachLine = br.readLine()
            while (eachLine != null) {
 
                if (eachLine.contains("old")) {
                    eachLine = eachLine.replace("old", "new")
                }
                sb.append(eachLine)
                sb.append("\n")
                eachLine = br.readLine()
            }

            FileUtil.writeTxt(sb.toString(), htmlFile)
    }
    fun writeTxt(msg:String,file:File) :Boolean{
        var fos :FileOutputStream? = null
        return try {
            fos = FileOutputStream(file)
            fos.write(msg.toByteArray())
            fos.flush()
            true
        } catch (e: Exception) {
            RLog.i(TAG, "writeTxt fail $e")
            false
        }finally {
            closeIo(fos)
        }
    }