如何在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(); 

但是这显示exception并且没有更新temp1和temp2。

您看到的exception – 我强烈建议a)捕获特定类型,例如IOException ,以及b)记录或显示消息或堆栈跟踪,以及c)至少在LogCat中检查,从如果您使用Eclipse编程,DDMS透视图可能是因为Android没有找到您尝试打开的config.txt文件。 通常,对于像您这样的最简单的情况,使用openFileInput打开应用程序专用的文件 -有关详细信息, 请参阅文档 。

除了exception之外,您的读取循环有缺陷:您需要在进入之前初始化空字符串,并在while条件下填充它。

 String line = ""; while ((line = br.readLine()) != null) { // do something with the line you just read, eg temp1 = line; temp2 = line; } 

但是,如果您只想将前两行保存在不同的变量中,则不需要循环。

 String line = ""; if ((line = br.readLine()) != null) temp1 = line; if ((line = br.readLine()) != null) temp2 = line; 

正如其他人已经指出的那样,调用readLine会消耗一行,所以如果你的config.txt文件只包含一行你的代码在while条件下使用它,那么temp1temp2会被赋值为null因为没有更多的文本可供读取。

 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)); String line = ""; while ((line = br.readLine()) != null) { temp1 = line; temp2 = line; } 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(); 

br.readLine()虽然已经消耗了一条线。

试试这个

  LineNumberReader reader = new LineNumberReader(new FileReader("config.txt"))); String line; while ((line = reader.readLine()) != null) { //doProcessLine } 

如果你想保存你必须要做的前两行:

 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)); String line = ""; if((line = br.readLine()) != null) temp1 = line; if((line = br.readLine()) != null) temp2 = line; } catch(Exception e) { e.printStackTrace(); }