Your daily dose of Java and related technologies.
News, Releases, Reviews, Tutorials, Articles, Events, Contests, Comments, Code and much more.
This java weblog is maintained by Xyling Technologies, making life simpler.

Sunday, September 10, 2006

Replacing a string in a file using Java

This code can really prove to be a life saver (hope I am not exaggerating an hour of programmer's time ;)

This is about replacing a string from a file in a given directory.


public static void replaceStringInFile(File dir, String fileName, String match, String replacingString){
try {
File file = new File(fileName);
if(file.isDirectory()){
//the fileName specified is not a file hence returning.
return;
}
file = new File(dir, fileName);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
long pointer = raf.getFilePointer();
String lineData = "";
while((lineData =raf.readLine()) != null){
pointer = raf.getFilePointer() - lineData.length()-2;
if(lineData.indexOf(match) > 0){
System.out.println("Changing string in file "+file);
raf.seek(pointer);
raf.writeBytes(replacingString);
//if the replacingString has less number of characters than the matching string line then enter blank spaces.
if(replacingString.length() < lineData.length()){
int difference = (lineData.length() - replacingString.length())+1;
for(int i=0; i < difference; i++){
raf.writeBytes(" ");
}
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch(Exception ex){
ex.printStackTrace();
}
}
}


Please feel free to use this code anywhere and if you wish to copy and paste it in your blog/site, would be great if you could link back :)

Anyone would like to extend/share a code that replaces a given character or any other similar useful variants are welcome. Use comments for the same.

This code has a small caveat. If the replacingString line is less lengthier than the line containg matching string pattern, then it inserts remaining blank spaces to clear it. Most of the times this may not be a problem but if it is do you suggest any other workaround?

[Resource-Type: Source-Code; Category: Java; XRating: 4]

6 Comments:

Anonymous Anonymous said...

Why cant we use replaceAll method of String. Now that we are using readLine, we could as well use replaceAll on eachh of the line. replaceAll method takes regex as "to-be-replaced" string. This presents much powerful proposition I guess. Ajitesh (http://www.simplihire.com)

2:46 PM

 
Blogger Xyling Technologies said...

If you use readline, you have to read everything till the end of file and write everything again after replacing.
This is particularly a problem when playing with large files.

8:17 AM

 
Anonymous Anonymous said...

This code has a bug, if the replacement String is longer than the original, it overwrites whatever next to the match including characters in the next line if the replacement is too long.

10:40 PM

 
Anonymous Anonymous said...

You r wrong man here is the code to replace a line or a string or a character in a file.

String tocmp="to set some value";
String strreplaced="this is the new value which will override the above";

FileReader inputFileReader =new FileReader("C:\\file.bat");
BufferedReader bfre=new BufferedReader(inputFileReader);
String Inline=null;
String wholefile="";

while((Inline = bfre.readLine())!=null)
{

System.out.println(Inline);
wholefile+=Inline+"\r\n";

}
inputFileReader.close();

wholefile=wholefile.replaceFirst(tocmp,strreplaced);

FileWriter outFileWriter=new FileWriter("C:\\file.bat");
outFileWriter.write(wholefile);
outFileWriter.close();

8:14 AM

 
Blogger Xyling Technologies said...

Hi anonymous,

Thank you very much for sharing the code with us.

Functionally, your code suggestion is correct.

How much time would that code take for processing a 500MB text fle or say 200 files of 250KB each?

If compare it with the code provided in the post, it would save some time because we are not reading the whole file and writing it back after changes.

The code do have some bugs but I wish people share their code the way you did.

Thanks a ton for your participation and contribution. Please keep sharing.

9:21 AM

 
Anonymous Anonymous said...

Hi Guys

Thank you for the posts.
I found a very interesting thing,
if you have any clue, or already come across this, please share it.

is there anyway to remove a string with question mark, just as in the case of xml declaration. I cannot put the same here in the post also.


I tried it and never removes as it(question mark) is present in a string.

thank you alll

6:58 PM

 

Post a Comment

<< Home