当我直接复制html文件的内容并将其存储在字符串中时,然后使用以下命令在webview中显示它:

mWebView.loadDataWithBaseURL("file:///android_asset/", myString, "text/html", "UTF-8", null);


一切都好!我想在加载到Webview之前(以编程方式)修改html文件的内容,但是当我使用以下代码从资产文件夹中读取html文件时

private String loadAssetTextAsString(Context context, String name) {
    BufferedReader in = null;
    try {
        StringBuilder buf = new StringBuilder();
        InputStream is = context.getAssets().open(name);
        in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        String str;
        boolean isFirst = true;
        while ( (str = in.readLine()) != null ) {
            if (isFirst)
                isFirst = false;
            else
                //buf.append('\n');
                buf.append(str);
        }
        return buf.toString();
    } catch (IOException e) {
        Log.e("TAG", "Error opening asset " + name);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Log.e("TAG", "Error closing asset " + name);
            }
        }
    }

    return null;
}


然后将其加载到webview中,该webview意外显示-字符(我认为其名称为软连字符)。我在HTML文件中使用UTF-8作为字符集。我也使用下面的代码删除-失败了。

myString = myString.replace("�", "");


如何移除�?谢谢你的帮助。

最佳答案

您的内容看起来像是编码为UTF-16,其中每个字符使用两个字节,而不是UTF-8中的一个字节。
简单ASCII字符在UTF-16中以空字节\0为前缀,当您尝试显示它时会转换为�。

因此,从InputStream读取为UTF-16可能会解决问题:

in = new BufferedReader(new InputStreamReader(is, "UTF-16"));




String.replace("�", "")不起作用,因为您看到的�符号与字符串中编码的符号不同。如果在解码过程中将其保留为UTF-8:\0,则直接替换空字节String.replace("\0", "")可能可行。

10-07 19:28
查看更多