android读取data/data/包名/file路径下的txt文件
16lz
2021-01-23
文件不能太大否则会报内存溢出
import java.io.FileInputStream;import org.apache.http.util.EncodingUtils;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class ReaddataPathActivity extends Activity { TextView textView; // 这个是读取data/data/包名/file路径下的文件 // 这个目录可以用getFilesDir()方法得到 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.tvtext); String txt = ""; try { // 获取文件 FileInputStream fin = openFileInput("name.txt"); // 获得长度 int length = fin.available(); // 创建字节数组 byte[] buffer = new byte[length]; // 读取内容 fin.read(buffer); // 获得编码格式 String type = codetype(buffer); // 按编码格式获得内容 txt = EncodingUtils.getString(buffer, type); textView.setText(txt); } catch(Exception e) { // TODO: handle exception } } private String codetype(byte[] head) { String type = ""; byte[] codehead = new byte[3]; System.arraycopy(head, 0, codehead, 0, 3); if(codehead[0] == -1 && codehead[1] == -2) { type = "UTF-16"; } else if(codehead[0] == -2 && codehead[1] == -1) { type = "UNICODE"; } else if(codehead[0] == -17 && codehead[1] == -69 && codehead[2] == -65) { type = "UTF-8"; } else { type = "GB2312"; } return type; }}
版权声明:本文为博主原创文章,未经博主允许不得转载。
更多相关文章
- android 验证手机号和邮箱格式
- android sdcard存储方案(基于fuse文件系统):之一
- 文件多线程下载实现
- Android EditText 格式化手机号 xxx xxxx xxxx
- 基于Android TV端的文件选择器(UI比较丑,主要看逻辑)
- Android学习笔记(八)之Android 读写xml文件
- Android札记:防反编译、混淆文件p…
- 总结android中的.gradle文件写法及含义
- [Android Studio] 使用本地 aar 文件