best approach to update text in file

J

jrefactors

If I want to read and replace text in a file called file.txt, I
should need to write it to a temporary file first, and then
delete file.txt, and then rename the temporary file to file.txt??

Here's the code fragment:

BufferedReader br = new BufferedReader(new FileReader(fileName));
PrintWriter out = new PrintWriter(new FileWriter(fileName + ".out"));
String line;
while ((line = br.readLine()) != null)
{ if (line.indexOf("XXX") != -1)
line = line.replaceFirst("XXX",replacement);
out.println(line);
}

please advise, thanks!!
 
K

kjc

If I want to read and replace text in a file called file.txt, I
should need to write it to a temporary file first, and then
delete file.txt, and then rename the temporary file to file.txt??

Here's the code fragment:

BufferedReader br = new BufferedReader(new FileReader(fileName));
PrintWriter out = new PrintWriter(new FileWriter(fileName + ".out"));
String line;
while ((line = br.readLine()) != null)
{ if (line.indexOf("XXX") != -1)
line = line.replaceFirst("XXX",replacement);
out.println(line);
}

please advise, thanks!!
Use MemoryMapped IO
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top