Android中读取中文字符的文件与文件读取相关
一、如何显示assets/license.txt(中文)的内容?
(1)方法1:InputStream.available()得到字节数,然后一次读取完。
private String readUserAgreementFromAsset(String assetName) {
String content ="";
try {
InputStream is= getAssets().open(assetName);
if (is != null){
DataInputStream dIs = newDataInputStream(is);
intlength = dIs.available();
byte[] buffer = new byte[length];
dIs.read(buffer);
content= EncodingUtils.getString(buffer, "UTF-8");
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
(2)方法2:用BufferedReader.readLine()行读取再加换行符,最后用StringBuilder.append()连接成字符串。
A.以下是先行读取再转码UTF8:
private String readUserAgreementFromAsset(String assetName) {
StringBuilder sb = newStringBuilder("");
String content ="";
try {
InputStream is= getAssets().open(assetName);
if (is != null){
BufferedReader d = newBufferedReader(new InputStreamReader(is));
while (d.ready()) {
sb.append(d.readLine() +"\n");
}
content =EncodingUtils.getString(sb.toString().getBytes(), "UTF-8");
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
B.以下是InputStreamReader先指定以UTF8读取文件,再进行读取读取操作:
private String readUserAgreementFromAsset(String assetName) {
StringBuilder sb = newStringBuilder("");
String content ="";
try {
InputStream is= getAssets().open(assetName);
if (is != null){
BufferedReaderd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while(d.ready()) {
sb.append(d.readLine() +"\n");
}
content= sb.toString();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
另外,UTF8转码也可以用new String(buffer, “utf-8”)。
(3)替代方法3:将license.txt内容作为string.xml的string,如:
<stringname="license_content">用户协议
\n \n一、服务条款的确认和接纳
\n…
</string>
需要注意的是:string里需要加\n作为换行符,原来txt里的换行符在取得string后无效。
不可取方法4:每次读取4096字节,以UTF8转码,最后连接字符串。因为汉字可能被截断,导致4096的倍数附近的中文可能出现乱码。
private String readUserAgreementFromAsset(String assetName) {
StringBuilder sb = newStringBuilder("");
String c
补充:移动开发 , Android ,