android 读 txt

引用:http://hi.baidu.com/hellofeng007/item/46dc22be62d99c442aebe3aa

android Files数据存储之读取txt文件 解决换行符变方格的问题

本代码是读取DDMS 下 Data-Data-Files-的txt文件

/*

*java 代码

*/

package ifeng.FileRW;   //这些包要切换成你自己的哦

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class FileRW extends Activity {
    /** Called when the activity is first created. */
  private TextView text = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);   
        
  
        text = (TextView)findViewById(R.id.t1);     

        char[] inputBuffer = new char[8000];    //这个视你们文本的大小决定
        String data = null;
      
        try{          


         //得到文件流对象

         FileInputStream myFileStream = openFileInput("1.txt"); 
         


         //得到读取器的对象,限制编码为GB2312

         InputStreamReader reader = new InputStreamReader(myFileStream,"gb2312");
              


         //将读取的流读进bufferedreader中
         BufferedReader myReader = new BufferedReader(reader);
         


         //再将bufferedreader读进inputbuffer里面,一个char型数组
         myReader.read(inputBuffer);
         


         //再将数据读进一个string类型的data里面
         data = new String(inputBuffer);

         data = data.replace("\r\n","\n");   //解决换行符变成空格的关键 

         //将数据用textview显示出来。

          text.setText(data);

          Toast.makeText(FileRW.this, "读取文件成功",Toast.LENGTH_SHORT).show();
            }
            catch (Exception e) {     
            e.printStackTrace();
            Toast.makeText(FileRW.this, "读取文件失败",Toast.LENGTH_SHORT).show();
            }

    }
}

/*

*main.xml 代码

*/

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
 android:id="@+id/t1" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>

 新手 不对的地方请指出~

原文地址:https://www.cnblogs.com/sode/p/2621551.html