android 读取assets文件下的txt文件,解决了读取txt文件的乱码问题;
package com.example.com.scrollview; import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView; public class MainActivity extends Activity { private TextView novel; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); novel = (TextView) findViewById(R.id.novel);
AssetManager am=getAssets();
try {
InputStream is=am.open("zx.txt"); String code=getCode(is);
is=am.open("zx.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(is,code)); String line=br.readLine();
int i=0;
while(line!=null){
novel.append(line+"\n");
line=br.readLine();
i++;
if(i==200){
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // novel.setText(readNovel()); } public String getCode(InputStream is){
try {
BufferedInputStream bin = new BufferedInputStream(is);
int p; p = (bin.read() << 8) + bin.read(); String code = null; switch (p) {
case 0xefbb:
code = "UTF-8";
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
default:
code = "GBK";
}
is.close();
return code;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}