2013-10-29 21 views
0

我有我想打印出包含字符串A/C NO:打印出來,從一個文件中的行,如果它包含某些字符串

import java.io.File; 
import java.io.FileReader; 
import java.io.IOException; 
import java.io.LineNumberReader; 
import org.apache.commons.io.FileUtils; 
public class TestFndString { 
    public static void main(String[] args) throws IOException { 
     String str1 = FileUtils.readFileToString(new File("C:/Testing.txt")); 
     LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:/Testing.txt"))); 
     lnr.skip(Long.MAX_VALUE); 
     if (str1.contains("A/C NO:")) { 
      int num = lnr.getLineNumber(); 
      System.out.println(num); 
     } 

    } 
} 
該行的文件

我的代碼是打印2爲其中包含的行號的字符串,而字符串其實就是在第3行,這裏是我的文件樣本:

jhsdjshdsjhdjs 
sdkjsdkjskdjskjd 
AjhsdjhsdjhA/C NO: jhsdjhsdjssdlk 

很顯然,我不相信這個讀取較大的文件或一組文件。做這個的最好方式是什麼?

回答

1

LineNumberReader從0開始,因此對於預期結果增加1。

DOCS

默認情況下,行號爲0開始於 此數目的增量每行終止符作爲數據被讀出,並且可以用 調用setLineNumber(INT)來改變。但是請注意,setLineNumber(int)確實不會改變流中的當前位置;它只有 更改將由getLineNumber()返回的值。

所以兩種方法可以得到預期的結果:

1. 

LineNumberReader lnr = new 
        LineNumberReader(new FileReader(new File("C:/Testing.txt")));   
    if (str1.contains("A/C NO:")) { 
     int num = lnr.getLineNumber(); 
     System.out.println(num+1); 
    } 




2. OR you can use setLineNumber(int) as mentioned in java docs. 
+0

如果我需要打印出包含字符串的A/C NO行:? – ErrorNotFoundException

+0

@Stanley多數民衆贊成在我這裏提到。 – Trying

+0

我的意思是整行字符串 – ErrorNotFoundException

1

行編號從0開始。只需將結果加1即可(請看JavaDoc)。您也可以致電setLineNumber(1)創建LineNumberReader後:

LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:/Testing.txt"))); 
lnr.setLineNumber(1); 
2

行號,像數組索引,以0開始遞增它與一個會給你正確的答案。

if (str1.contains("A/C NO:")) { 
    int num = lnr.getLineNumber(); 
    System.out.println(++num); // see the increment using ++ ? 
} 

預先遞增運營商將通過1遞增num變量可以在打印前,因此你會得到期望的結果。

相關問題