2014-04-04 52 views
1

我想讓程序找到「[DesiredText]」並檢查下一行是否爲空,然後如果是我想取空行的位置。我看到一些例子,但我不能正常工作。歡迎所有建議和線索。如何檢查文本文件中的下一行是否爲空?

BufferedReader br = new BufferedReader(new FileReader(file)); 

String line = null; 

while ((line = br.readLine()) != null) { 

if ((line.contains("[DesiredText]") && br.readLine().isEmpty())) { 

       RandomAccessFile raf = new RandomAccessFile("D:\\Temp.txt","r"); 
       long position = raf.getFilePointer(); 
       pozycje.add(position); 
       raf.close(); 


     } 
} 
+1

_I無法正常工作_怎麼樣? –

回答

2

讀線,然後檢查

if("".equals(line)) 

或者,如果你不想算白空間:

if("".equals(line.trim())) 

另外,如果你有一個像while ((line = br.readLine()) != null)一個循環由br.readLine()的值控制,您應該而不是再次在循環內調用br.readLine()。這可能會導致您越過循環內文件的末尾並出現錯誤。

你應該做的是在找到line.contains("[DesiredText]")後設置一個標誌,然後在下一個循環(下一行)中檢查該標誌是否設置爲空。

0

你可以跟蹤到目前爲止你已經閱讀的字符串+換行符的長度,一旦你得到一個空行,length變量應該給你空行的位置。

0

您可以創建兩個RandomAccessFiles,其中第二個將比第一個更遠。例如:

RandomAccessFile first = new RandomAccessFile("D:\\Temp.txt","r"); 
    RandomAccessFile second = new RandomAccessFile("D:\\Temp.txt","r"); 

    String line; 
    String nextLine = second.readLine(); 

    while (nextLine != null) { 
     line = first.readLine(); 
     nextLine = second.readLine(); 

     if ((line.contains("[DesiredText]") && nextLine.isEmpty())) { 
      pozycje.add(first.getFilePointer()); 
     } 
    }