xrk*_*lix 2 java android file-handling
我正在使用此代码.
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();
Run Code Online (Sandbox Code Playgroud)
但是这显示异常并且没有更新temp1和temp2.
唯一的例外,你看-我会强烈建议)来捕捉一个特定的类型,例如IOException
,和b)登录或消息或堆栈跟踪显示,和c)至少在logcat的检查,从DDMS透视图,如果您使用Eclipse编程 - 可能是因为Android没有找到config.txt
您尝试打开的文件.通常,对于像您这样的最简单的情况,使用openFileInput
- 打开应用程序专用的文件 -有关详细信息,请参阅文档.
除了异常之外,您的读取循环有缺陷:您需要在输入之前初始化空字符串,并在while
条件中填充它.
String line = "";
while ((line = br.readLine()) != null) {
// do something with the line you just read, e.g.
temp1 = line;
temp2 = line;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您只想将前两行保存在不同的变量中,则不需要循环.
String line = "";
if ((line = br.readLine()) != null)
temp1 = line;
if ((line = br.readLine()) != null)
temp2 = line;
Run Code Online (Sandbox Code Playgroud)
正如其他人已经指出,通话readLine
占用一条线,所以如果你的config.txt
文件只包含一行代码消耗它的while
条件,然后temp1
和temp2
得到null
分配,因为没有更多的文本阅读.
归档时间: |
|
查看次数: |
20241 次 |
最近记录: |