最近在项目中遇到了一个很奇怪的问题,将assets目录下的json文件读取出来后出现乱码,检查项目编码格式统一是utf-8。读取assets的方法为
public static String getJson(Context mContext, String fileName) {
StringBuilder sb = new StringBuilder();
InputStream input = mContext.getClass().getClassLoader().getResourceAsStream("assets/" +
fileName);
try {
byte[] b = new byte[4096];
for (int n; (n = input.read(b)) != -1; ) {
sb.append(new String(b, 0, n));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
sb.delete(0, sb.length());
}
return sb.toString().trim();
}
网上求助后尝试修改为如下:
public static String getJson(Context context, String fileName) {
String resultString = "";
try {
InputStream inputStream = context.getResources().getAssets().open(fileName);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
resultString = new String(buffer, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
}
return resultString;
}
应该是读取assets时候默认转码的问题,指定utf-8后正常显示。