You're trying to read and write to the same file at the same time. While there may be a way of getting that to work, it's going to be fiddly.
I suggest you read from file A and write to file B - and if you want to effectively replace the input file, then you can do that with a sequence of moves and deletes at the end.
A few other suggestions:
- You should have try/finally blocks to close both the input and the output at the end.
- You don't need to use a
DataInputStream
- you're not using anything from it. Just wrap the input stream directly.
- I suggest you specify the encoding explicitly both for input and output rather than trusting the default encoding. (I wish
FileWriter
and FileReader
accepted encodings in their constructors.)
- It's more robust to use
OutputStreamWriter
(or something similar) rather than PrintWriter
- currently you're not going to detect if anything goes wrong when you're writing.
So something like this:
// Ideally have this as a constant somewhere.
Charset utf8 = Charset.forName("UTF-8");
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(inputFile), utf8);
try {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile), utf8);
String line;
while ((line = reader.readLine()) != null) {
if (!line.contains(name)) {
writer.write(line);
writer.newLine();
}
}
} finally {
writer.close();
}
} finally {
reader.close();
}
// Now if you want to shift files around, do it here
It's a shame that Java makes this so fiddly with the try/finally blocks. Oh for C#'s using
statements...