2013-12-16 21 views
0

我有寫代碼來打印文本文件的全部文本,但我可以不知道如何使它能夠閱讀全文除了最後一行如何讀取除最後一行以外的文本文件中的整個文本?

驗證碼:

public class Files { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    // TODO code application logic here 
    // -- This Code is to print the whole text in text file except the last line >>> 
    BufferedReader br = null; 
    try { 
     String sCurrentLine; 
     br = new BufferedReader(new FileReader("FileToPrint.txt")); 
     String s = br.readLine(); 
     while (true) { 
      if ((sCurrentLine = br.readLine()) != null) { 
       System.out.println(s); 
       s = sCurrentLine; 
      } 
      if ((sCurrentLine = br.readLine()) != null) { 
       System.out.println(s); 
       s = sCurrentLine; 
      } else { 
       break; 
      } 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null) { 
       br.close(); 
      } 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 


} 

}

我想上面的代碼可以讀除了最後一行文字,,,

感謝您的幫助

+0

你爲什麼在循環中讀兩行? –

回答

0

有沒有辦法WRI您的程序,以便它不閱讀最後一行;該程序必須讀取最後一行,然後嘗試另一次讀取,然後才能確定該行是最後一行。你需要的是一個「向前看」算法,這將是這個樣子的僞代碼:

read a line into "s" 
loop { 
    read a line into "nextS" 
    if there is no "nextS", then "s" is the last line, so we break out of the 
     loop without printing it 
    else { 
     print s 
     s = nextS 
    } 
} 
1

最簡單的方法可能是每次打印以前行:

String previousLine = null; 
String line; 
while ((line = reader.readLine()) != null) { 
    if (previousLine != null) { 
     System.out.println(previousLine); 
    } 
    previousLine = line; 
} 

我'd還建議避免捕獲異常,如果你只是打印出來然後繼續 - 你最好使用try-with-resources語句關閉讀者(如果你使用的是Java 7)並聲明你的方法拋出IOException

+0

拜託,這不是我的問題..我的問題最簡單的方法是:是否有一種方法可以讀取除最後一行 – user2976643

+1

@ user2976643之外的全文:然後,您需要澄清您的問題。這將打印出除了文件的最後一行以外的所有內容,我認爲這是你想要實現的。如果你試圖真正避免*閱讀*最後一行,那麼如何知道你是否已經*到最後一行? –

相關問題