如何在android中逐行读取?
我正在使用这个代码。
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。
i am using this code.
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();
but this is showing exception and is not updating temp1 and temp2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您看到的异常 - 我强烈建议a)捕获特定类型,例如
IOException
,b)记录或显示消息或堆栈跟踪,c)至少如果您使用 Eclipse 进行编程,请从 DDMS 的角度检查 LogCat - 可能是由于 Android 找不到您尝试打开的config.txt
文件。通常,对于像您这样的最简单的情况,应用程序私有的文件是使用openFileInput
打开的 - 有关详细信息,请参阅文档。除了异常之外,您的读取循环有缺陷:您需要在输入之前初始化一个空字符串,并将其填充到
while
条件中。但是,如果您只想将前两行保存在不同的变量中,则不需要循环。
正如其他人已经指出的那样,调用 readLine 会消耗一行,因此如果您的 config.txt 文件仅包含一行,您的代码会在 while 上消耗它code> 条件,则
temp1
和temp2
会被分配null
,因为没有更多文本可供读取。The exception you see - that I would strongly recommend a) to catch as a specific type, e.g.
IOException
, and b) to log or show with a message or a stack trace, and c) at least to check for in LogCat, from the DDMS perspective if you are programming with Eclipse - is probably due to Android not finding theconfig.txt
file you are trying to open. Usually, for the simplest cases such as yours, files that are private to an application are opened usingopenFileInput
- see the documentation for details.Apart from the exception, your reading loop is defective: you need to initialize an empty string before entering, and fill it in the
while
condition.However, you don't need a loop if you just want to save the first two lines in different variables.
As others have already pointed out, calling
readLine
consumes a line, so if yourconfig.txt
file contains only one line your code consumes it on thewhile
condition, thentemp1
andtemp2
getnull
assigned because there's no more text to read.while 中的 br.readLine() 已经消耗了一行。
试试这个
br.readLine() in while already consumes a line.
Try this
如果你想保存前两行,你必须这样做:
if you want to save the first two lines you have to do: