File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Problem while replacing line with another string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem while replacing line with another string" Watch "Problem while replacing line with another string" New topic

Problem while replacing line with another string

Rahul B. Shah

Joined: Jan 17, 2011
Posts: 24
i have following .txt file

aaa<!--app name-->aaa

I want to replace <!--UserID-->,<!--app name-->,<!--Error-->,<!--LDAPGroup-->,so output should be


I have written following code which replaces only last line aaa<!--LDAPGroup-->aaa

private String getForm1(String app,String userId,String error,String ldapGrp){

String replaceStr="";
BufferedReader br;


File file = new File("input.txt");
br = new BufferedReader(new FileReader(file));
String line="";
String oldText="";
String newText="";

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

oldText += line + "\r\n";



newText = oldText.replaceAll("<!--UserID-->",userId);

newText = oldText.replaceAll("<!--app name-->",app);

newText = oldText.replaceAll("<!--Error-->",error);

newText = oldText.replaceAll("<!--LDAPGroup-->",ldapGrp);

FileWriter writer = new FileWriter("input.txt");

System.out.println("Done ...");

}catch(Exception e){

System.out.println("Exception :"+ e.toString());

return replaceStr;

Rahul Shah
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

First, please UseCodeTags(⇐click) so that your code will be readable.

Second, note that replaceAll takes a regex as it's input, not just a plain old String. You have at least one character in your input that's special to regex. I'm surprised it's working at all. Either form a proper regex, or use the simple replace() method, which doesn't use regex.

Finally, look at your code, carefully:

What, exactly, do you think the first line will do?

What, exactly, do you think the second line will do?

Imagine you're the JVM, very carefully execute those first two lines with pencil and paper. If you do that correctly, you'll have your answer.
I agree. Here's the link:
subject: Problem while replacing line with another string
It's not a secret anymore!