• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Problem while replacing line with another string

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
i have following .txt file

aaa<!--UserID-->aaa
aaa<!--app name-->aaa
aaa<!--Error-->aaa
aaa<!--LDAPGroup-->aaa

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

aaaRahulaaa
aaaMyAppaaa
aaaMyErroraaa
aaaMyLDAPaaa

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;

try{

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";

}

br.close();

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");
writer.write(newText);
writer.close();

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

}catch(Exception e){

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

return replaceStr;
}

Thank-You
Rahul Shah
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic