2016-11-23 78 views
-3
工作

我已經在一個名爲Sample.txt的簡單的線替換未在Java中

This is line1 
This is line2 

這裏一個文本文件,我想更換新線下面的內容,我的意思是輸出應該像

This is line1 and This is line2 

和我的代碼如下。

BufferedReader br = null;

try { 

    String sCurrentLine; 

    br = new BufferedReader(new FileReader("C:\\Users\\home\\Desktop\\Test\\Sample.txt")); 
    int i = 0; 
    while ((sCurrentLine = br.readLine()) != null) { 

     String sCurrentLine1 = sCurrentLine.replaceAll("\\n+", "0NL0"); 
     System.out.println("Line No." + i + " " + sCurrentLine1); 
     i++; 
    } 

當我打印,我得到的輸出作爲

Line No.0 This is line1 
Line No.1 This is line2 

請讓我知道我可以取代這個新的生產線。

感謝

+1

根據定義'的readLine()'讀取_single_線和不包括結束換行符。 –

+0

是你關於替換不工作的問題(因此你不能在你的結果中看到'0NL0'),或者你只是希望輸出全部在1行?對於後者,請使用'print'而不是'println' –

回答

1

你不需要做replaceAllBufferedReader::readLine()方法從sCurrentLine中返回的字符串中刪除\n字符。所以你所要做的就是添加返回的行。

實施例:

try { 

String sCurrentLine; 
StringBuilder sb = new StringBuilder();// Declare a string builder object. 
br = new BufferedReader(new FileReader("C:\\Users\\home\\Desktop\\Test\\Sample.txt")); 
int i = 0; 
while ((sCurrentLine = br.readLine()) != null) { 
    if(i>0) { 
     sb.append(" and "); 
    } 
    sb.append(sCurrentLine); 
    System.out.println("Line No." + i + " " + sCurrentLine); 
    i++; 
} 
System.out.println("Appended output " + sb.toString()); 
-1

試試這個,

String str = ""; 
while ((sCurrentLine = br.readLine()) != null) { 

    String sCurrentLine1 = sCurrentLine.replaceAll("\\n+", "0NL0"); 
    str = str + sCurrentLine1 + " and "; 
} 
System.out.println(str.substring(0,(str.length()-5))); 

希望它可以幫助你。

+0

嗨,朋友,這個效果很好,但是我得到null打印作爲第一個結果,然後實際結果。 'nullThis is line1 and this is line2' – user3872094

+0

thnx,i edited that – PSabuwala