我已经研究了很多不同的解决方案来解决这个问题,但似乎没有任何效果。
我正在尝试制作一个读取文本文件并将其部分内容显示在屏幕上的应用程序。我在读取文件时遇到问题,而且我不知道我做错了什么。我一直在调试代码,它抛出一个 IO java 异常(fileNotFound)..它不执行代码的文件读取部分..我从未到达 while 循环..它在我到达它之前抛出异常.
我把文件放在/res/raw目录
LogCat 中的错误输出为:threadid=3 Thread exiting due to uncaught exception
当我编译代码时,它还在第 48 行提示 nullPointerException,我不明白,因为我似乎没有到达调试器中的那部分代码。
我做错了什么?
public class AndroidReadTest extends Activity {
HashMap<String, ArrayList<String>> table = new HashMap();
Random rand = new Random();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String category = "";
ArrayList<String> temp = new ArrayList();
try {
/** AssetFileDescriptor descriptor = getAssets().openFd("AndroidReadTest/res/raw/questions");
BufferedReader in = new BufferedReader(new FileReader(descriptor.getFileDescriptor())); */
BufferedReader in = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.questions))); // I have tried adding .txt
while(in.readLine()!=null){
......
}
table.put(category, temp);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(click);
}
public String get(ArrayList<String> questions){
int temp = questions.size();
String str = questions.get(rand.nextInt(temp));
return str;
}
private OnClickListener click = new OnClickListener(){
public void onClick(View V){
TextView text = (TextView) findViewById(R.id.textView1);
text.append(get(table.get("---Cathegory")));
}
};
}
最佳答案
尝试将文本文件放入项目的 asset 文件夹中,而不是 res/raw 中。
This page has a nice overview如何存储文件。
AssetManager是您从 Activity 中访问它们的方式。
关于java - Android应用程序,从res读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8806657/