Saturday, August 8, 2009

Replacing String In File


Hi Reader,

It's going to be my second post.
This post is not as a rocket science but needful.
I got idea to create this program, when i got issue with my module.
There was an xml document and i need to know the occurances of a particular string.
The file size was more than 10 mb. I used edit plus for this. First it took time for loading file in edit plus and then when i tried hit "ctrl + h" (to find and replacce dialog box) duhh! Got hanged.
Then i used my program. And felt glad.

Please have look may be it ll be helpful for you also.

This program replaces all the occurances of a given string to be replaced in the given file with the given string to be replaced by.


package src;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ReplaceDataInFile {
public static void main(String args[]) {
ReplaceDataInFile ob = new ReplaceDataInFile();
ob.replaceStringInFile("C:\\_T_Work", "file.txt", "old", "new");
}


private void replaceStringInFile(final String fileLoc, final String fileName, final String toReplace, final String replaceBy) {

File file = null;
BufferedReader br = null;
BufferedWriter bw = null;
String currentLine = "";
String oldContentOfFile = "";
int occuranceFound = 0;
int countLine = 0;


try {
file = new File(fileLoc + System.getProperty("file.separator") + fileName);
br = new BufferedReader(new FileReader(file));

while ((currentLine = br.readLine()) != null) {
countLine++;
oldContentOfFile = oldContentOfFile + currentLine + "\r\n";
System.out.println("Line " + countLine + " : " + currentLine);

if (currentLine.contains(toReplace)) {
occuranceFound++;
}
}

} catch (IOException e) {
System.out.println("Error Occured When Reading File : " + e);
System.exit(1);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.println("Error Occured When Closing Reader : " + e);
System.exit(1);
}
}
}


System.out.println();
System.out.println("Old Content of The File : ");
System.out.println(oldContentOfFile);

String latestText = oldContentOfFile.replaceAll(toReplace, replaceBy);
System.out.println("Latest Content of The File : ");
System.out.println(latestText);


try {
bw = new BufferedWriter(new FileWriter(fileLoc + System.getProperty("file.separator") + fileName));
bw.write(latestText);
System.out.println("Total [" + occuranceFound + "] Occurances of ["
+ toReplace + "] Replaced By [" + replaceBy + "].");
} catch (IOException e) {
System.out.println("Error Occured When Writtin To File : " + e);
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
System.out.println("Error Occured When Closing Writer : " + e);
System.exit(1);
}
}
}
}
}




To execute this just change the paramter of the method called in main().

Waiting for your responses.

Thanks,
Tanzy.