2011-08-16 11 views
-2

1つの.txtファイルから2行を取り出してダイアログボックスに出力する必要があります。現在のコードは特定の行を読む - 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とbaseStartLine = 2

答えて

2

あなたは決して実際に任意の行をスキップしませんよ。別の番号からループインデックスを開始しますが、ファイルの先頭からループを1回だけ行います。

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

しかしあなたのループは次のようになります。ファイルの最初の2行だけを読みたいので、最初に両方読むことができます:

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

ありがとうございます! – RayCharles

0

これは正しいです。両方の方法でファイルの最初の行だけを読み込みます。新しいreaderを作成し、die readLine()メソッドで行を読み込むと、リーダーはファイルの最初の行を返します。あなたのfor-loopの番号にかかわらず。

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

これは読んで1ライン分のシンプルなソリューションです。

最初の行ではforループは必要ありません。リーダを作成してreadLine()メソッドを呼び出すことができます。これは最初のLineを返します。

関連する問題