Android 读取assets文件下的txt文件

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

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; 
}
}


标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:一个PHP分页函数

下一篇: iOS的AES加解密