2011-08-16 56 views
-2

我需要从1 .txt文件中检索两行并将它们输出到对话框。我以现在的代码是阅读特定行 - Java

private String getfirstItem() { 
    String info = ""; 
    File details = new File(myFile); 
    if(!details.exists()){ 
      try { 
       details.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     BufferedReader read = null; 
    try { 
     read = new BufferedReader (new FileReader(myFile)); 
    } catch (FileNotFoundException e3) { 
     e3.printStackTrace(); 
    } 

    for (int i = baseStartLine; i < baseStartLine + 1; i++) { 
        try { 
       info = read.readLine(); 
       } catch (IOException e) { 

        e.printStackTrace(); 
       } 
      } 
      firstItem = info;    
      try { 
       read.close(); 
     } catch (IOException e3) { 

      e3.printStackTrace(); 
     } 
      return firstItem; 
} 

private String getsecondItem() { 
    File details = new File(myFile); 
    String info = ""; 
    BufferedReader reader = null; 
    if(!details.exists()){ 
try { 
    details.createNewFile(); 
} catch (IOException e) { 
    e.printStackTrace(); 

}} 



try { 
reader = new BufferedReader (new FileReader(myFile)); 
} catch (FileNotFoundException e3) { 
    e3.printStackTrace(); 
    } 

for (int i = modelStartLine; i < modelStartLine + 1; i++) { 
      try { 
    info= reader.readLine(); 
      } catch (IOException e) { 
     e.printStackTrace();} 
     modelName = info;} try { 
      reader.close(); 
} catch (IOException e3) { 
    e3.printStackTrace(); 
    } 
return secondItem; 
} 

不过,我不断收到两个相同的值? modelStartLine = 1 and baseStartLine = 2

回答

2

你永远不会真的跳过任何行。你从一个不同的数字开始你的循环索引,但是你仍然只从文件开始循环一次。你的循环应该是这个样子:

public string readNthLine(string fileName, int lineNumber) { 
    // Omitted: try/catch blocks and error checking in general 
    // Open the file for reading etc. 

    ... 

    // Skip the first lineNumber - 1 lines 
    for (int i = 0; i < lineNumber - 1; i++) { 
     reader.readLine(); 
    } 

    // The next line to be read is the desired line 
    String retLine = reader.readLine(); 

    return retLine; 
} 

现在,你可以调用该函数是这样的:

String firstItem = readNthLine(fileName, 1); 
String secondItem = readNthLine(fileName, 2); 

然而。因为你只想文件的前两行,你可以阅读他们俩最初:

// Open the file and then... 
String firstItem = reader.readLine(); 
String secondItem = reader.readLine(); 
+0

非常感谢! – RayCharles

0

这是对的。你只用两种方法读取文件的第一行。当您创建一个新的Reader并使用readLine()方法读取一行时,阅读器将返回该文件的第一行。不管你的for循环中的数字如何。

for(int i = 0; i <= modelStartLine; i++) { 
    if(i == modelStartLine) { 
     info = reader.readLine(); 
    } else { 
     reader.readLine(); 
    } 
} 

这是一行读取的简单解决方案。

对于第一行,您不需要for循环。您可以创建阅读器并调用readLine()方法。这返回第一行。