2016-11-23 83 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