在Android代码中读取文件时出现异常

时间:2013-11-03 10:09:15

标签: java android file file-handling

No Assests Folder in Herarichy Location of the file我的android项目的assets文件夹中有一个文件“myFile.txt”,我试图在我的android代码中读取它的文本,如下所示:

    String filename= "myFile.txt";

    InputStream inputStream;

    try {

        inputStream = getAssets().open(filename) ;
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String text = br.readLine();
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
        TextView tw = (TextView) findViewById(R.id.hello);
        tw.setText(text);
        br.close();
        inputStream.close();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        //e.printStackTrace();
    }

应用程序不会崩溃,尽管它会在catch块中显示带有文本“myFile.txt”的toast。帮我。等待。

1 个答案:

答案 0 :(得分:1)

正如错误所说,Android无法找到您要求他查找的文件。 您应首先验证文件是否在此处(例如,不在assets/txt中,也不在/build/assets/中)。

MainProjectFolder
|--> res
|--> src
|--> assets
    |--> yourFile.txt

然后以这种方式访问​​其内容:

    String everything = "";

    AssetManager am = context.getAssets();
    InputStream is = am.open(filename);
    BufferedReader br = new BufferedReader(is);
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append('\n');
            line = br.readLine();
        }
        everything = sb.toString();
    } finally {
        br.close();
        inputStream.close();
    }

    TextView tw = (TextView) findViewById(R.id.hello);
    tw.setText(everything);