Wednesday, August 29, 2007

String replace in a File


This is the code to replace the existing String with the given String in a given file present in the given directory.

Code:

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

2 comments:

shivani said...
This comment has been removed by the author.
shivani said...

Its incorrect. Some of the code snippet is missing.
like "for" loop.
Also it's copied from some where that too not properly