读取txt文件并在Android中输出为TextView

use*_*438 1 android text ioexception

我正在尝试读取已保存在我的目录中的文本文件,并将其作为TextView打印在屏幕上.这是我到目前为止的代码.但是,当我运行应用程序时,它会创建一个"错误读取文件"的Toast.我在这做错了什么?

public class sub extends Activity {

private TextView text;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.text);
    //text = (TextView) findViewById(R.id.summtext);
    //File file = new File("inputNews.txt");        
    //StringBuilder text = new StringBuilder();
    try {
        InputStream in = openFileInput("inputNews.txt");

        if(in != null){
            InputStreamReader reader = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(reader);
            StringBuilder text = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }   
            in.close();            

        }

    }
    catch (IOException e) {
        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }


    TextView output= (TextView) findViewById(R.id.summtext);
    output.setText((CharSequence) text);

}

}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Nar*_*aki 9

如果要.txt在项目中保留文件,则必须将其放在assets文件夹中.
然后您可以使用AssetManger访问它.
阅读主题有关如何创建assets文件夹,然后使用此代码:

public class subActivity extends Activity {

private TextView textView;
private StringBuilder text = new StringBuilder();

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.text);
    BufferedReader reader = null;

    try {
        reader = new BufferedReader(
            new InputStreamReader(getAssets().open("inputNews.txt")));

        // do reading, usually loop until end of file reading  
        String mLine;
        while ((mLine = reader.readLine()) != null) {
            text.append(mLine);
            text.append('\n');
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
        e.printStackTrace();
    } finally {
        if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            //log the exception
        }
    }

    TextView output= (TextView) findViewById(R.id.summtext);
    output.setText((CharSequence) text);

 }
}
Run Code Online (Sandbox Code Playgroud)