我正在使用这个代码。
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("config.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((br.readLine()) != null) {
temp1 = br.readLine();
temp2 = br.readLine();
}
in.close();
}catch (Exception e){//Catch exception if any
Toast.makeText(getBaseContext(), "Exception", Toast.LENGTH_LONG).show();
}
Toast.makeText(getBaseContext(), temp1+temp2, Toast.LENGTH_LONG).show();
但这显示异常并且没有更新 temp1 和 temp2。
您看到的异常 - 我强烈建议 a) 捕获特定类型,例如IOException
,b) 记录或显示消息或堆栈跟踪,c) 至少在 LogCat 中检查,如果您使用 Eclipse 进行编程,则从 DDMS 角度来看 - 可能是由于 Android 未找到config.txt
您试图打开的文件。通常,对于像您这样的最简单的情况,应用程序私有的文件是使用以下命令打开的openFileInput
- 请参阅文档 http://developer.android.com/reference/android/content/Context.html#openFileInput%28java.lang.String%29了解详情。
除了异常之外,您的读取循环有缺陷:您需要在输入之前初始化一个空字符串,并将其填充到while
健康)状况。
String line = "";
while ((line = br.readLine()) != null) {
// do something with the line you just read, e.g.
temp1 = line;
temp2 = line;
}
但是,如果您只想将前两行保存在不同的变量中,则不需要循环。
String line = "";
if ((line = br.readLine()) != null)
temp1 = line;
if ((line = br.readLine()) != null)
temp2 = line;
正如其他人已经指出的那样,调用readLine
消耗一条线,所以如果你的config.txt
文件仅包含一行,您的代码在while
条件,则temp1
and temp2
get null
已分配,因为没有更多文本可供阅读。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)