如何在android中逐行阅读?

时间:2011-10-28 10:05:45

标签: 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();

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

4 个答案:

答案 0 :(得分:7)

您看到的例外情况 - 我强烈建议您抓住特定类型,例如: {},} b)使用消息或堆栈跟踪进行日志记录或显示,以及c)至少要在LogCat中检查,如果使用Eclipse进行编程,则从DDMS角度检查 - 可能是由于Android未找到您尝试打开的IOException文件。通常,对于像您这样的最简单的情况,使用config.txt - see the documentation打开应用程序专用的文件以获取详细信息。

除了例外,您的阅读循环有缺陷:您需要在输入前初始化空字符串,并将其填入openFileInput条件。

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条件下使用它,那么{{1分配了whiletemp1,因为没有更多要阅读的文字了。

答案 1 :(得分:1)

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();

答案 2 :(得分:1)

br.readLine()in while已消耗一行。

试试这个

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

答案 3 :(得分:0)

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

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();
}