This post originated from an RSS feed registered with Java Buzz
by Goldy Lukka.
Original Post: Replacing a string in a file using Java
Feed Title: Xyling Java Blogs
Feed URL: http://www.javablogs.xyling.com/thisWeek.rss
Feed Description: Your one stop source for Java Related Resources.
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 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?
I think there is a simple way of handling replace string and match string length variations. Instead of manipulating file contents directly, replace match string with replace string using string replace on linedata and writing entire linedata to file.
Like this : lineData = lineData.replace(match, replacingString); raf.writeBytes(lineData);