I want to delete some content of file using java program as below. Is this the write method to replace in the same file or it should be copied to the another file.
But its deleting the all content of the file.
class FileReplace
{
ArrayList<String> lines = new ArrayList<String>();
String line = null;
public void doIt()
{
try
{
File f1 = new File("d:/new folder/t1.htm");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while (line = br.readLine() != null)
{
if (line.contains("java"))
line = line.replace("java", " ");
lines.add(line);
}
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
out.write(lines.toString());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public statc void main(String args[])
{
FileReplace fr = new FileReplace();
fr.doIt();
}
}
I would start with closing reader, and flushing writer:
The accepted answer is slightly wrong. Here's the correct code.
Make sure to:
close
any stream when you no longer need themtruncate
the file, to make sure it shrinks if you write less than it had.toString
.flush
andclose
when you are finished writing!If you use buffered IO, you always have to ensure that the buffer is flushed at the end, or you might lose data!
Read + write to the same file simulatenously is not ok.
EDIT: to rephrase and be more correct and specific - reading and writing to the same file, in the same thread, without properly closing the reader (and flusing the writer) is not ok.
I can see three problems.
First you are writing to
out
which I assume is System.out, not an output stream to the file.Second, if you do write to an output stream to the file, you need to close it.
Third, the
toString()
method on anArrayList
isn't going to write the file like you are expecting. Loop over the list and write eachString
one at a time. Ask yourself whether you need to write newline characters as well.The accepted answer is great. However, there is an easier way to replace content in a file using Apache's
commons-io
library (commons-io-2.4.jar
- you can use any latest versions)Note: Thrown
IOException
needs to be caught and handled by the application accordingly.