topper1309 topper1309 - 22 days ago 8
Java Question

How to replace a word in an exisiting text file in java

I want to replace a word to another word in an existing text file. I think my code is correct but whenever I run the program all the text gets deleted in the text file.

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

// FILE TEST
public class Test {
public static void main(String ar[]) throws IOException{

String getText, putText;
File f = new File("Test.txt");
FileReader fr ;
BufferedReader br ;
BufferedWriter bw;
if(f.exists()){
try{
fr = new FileReader(f);
br = new BufferedReader(fr);
bw = new BufferedWriter(new FileWriter(f));
while((getText = br.readLine()) != null){
System.out.println(getText);
if(getText != null){
putText = getText.replaceFirst("Dog", "Cat");
bw.write(putText);
}
}
bw.close();
br.close();
}
catch(IOException e){
e.printStackTrace();
}
}else{
System.out.println("No File exists!");
}
}
}

Answer

You simply should not read and write from/to the same file at the same point in time.

Instead: read from file A; and write to some file A.tmp.

And if you absolutely want to, you can still delete A, and rename A.tmp to A in the end.

Finally, just for the record: if your goal is really just that; to replace some strings in some text file, the more reasonable answer would be to look into tools such sed (or some alternatives that exist for Windows OSes).