Coding Tips (JavaScript/CSS/VBA/Win32)
Useful code snippets, tips and some Windows applications
Find and Replace Occurencies of a String In the same file
Description:
You need to replace all occurencies of a string in a text file
Solution: (For Java 1.4 and higher)
Use the following method:
public static void readReplace(String fname, String oldPattern, String replPattern){ String line; StringBuffer sb = new StringBuffer(); try { FileInputStream fis = new FileInputStream(fname); BufferedReader reader=new BufferedReader ( new InputStreamReader(fis)); while((line = reader.readLine()) != null) { line = line.replaceAll(oldPattern, replPattern); sb.append(line+"\n"); } reader.close(); BufferedWriter out=new BufferedWriter ( new FileWriter(fname)); out.write(sb.toString()); out.close(); } catch (Throwable e) { System.err.println("*** exception ***"); } }The method reads a file line by line, replaces a string in each line if any, appends the resulting line to a StringBuffer. After all the file has been read to a StringBuffer, it is written to the same file. The argumens to the String.replaceAll method must follow the regular expression pattern rules.
-
Usage:
readReplace("filename.txt", "Russia", "China");
More Java Tips
Create Sub-Directory From File Name
Read File Contents into ArrayList