gpt4 book ai didi

java - Android代码读取文件异常

转载 作者:行者123 更新时间:2023-12-01 13:53:52 25 4
gpt4 key购买 nike

No Assests Folder in Herarichy Location of the file我的 android 项目的 asset 文件夹中有一个文件“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 block 中显示带有文本“myFile.txt”的 toast。帮我。等待。

最佳答案

正如错误所说,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);

关于java - Android代码读取文件异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19751793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com