I want to replace a word from a txt file in java. I already have my regular expression and the method for reading the txt file from java. But i have no idea how to replace a word from it using mu regualar expression.
Any suggestion or example?
I want to replace a word from a txt file in java. I already have my regular expression and the method for reading the txt file from java. But i have no idea how to replace a word from it using mu regualar expression.
Any suggestion or example?
public class BTest
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
// replace a word in a file
String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
//String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Parse the file into one string.Then replace all instances of word with new word.
String response = "test string".replaceAll("regex here", "new text");
Then write the new text to a file
FileWriter writer = new FileWriter("out.txt");
writer.write(response);