-1

Herarichy 中没有资产文件夹文件位置我的 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();
    }

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

4

1 回答 1

1

正如错误所说,Android 找不到您告诉他要查找的文件。您应该首先验证文件是否在这里(而不是,例如 inassets/txt或 in /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);
于 2013-11-03T10:26:25.577 回答