我的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。帮我。等待。
答案 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);