tags:

views:

1975

answers:

3

I was digging on the internet to find a small code snippet that will find a line in file and remove that line (not content but line) but could not find. So for example I have in a file following:

File myFile.txt

aaa
bbb
ccc
ddd

Need to have a function like this: public void removeLine(String lineContent), and if I pass removeLine("bbb"), i get file like this:

File myFile.txt

aaa
ccc
ddd

Please help me to find a solution. Thanks in advance.

+5  A: 

This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.

File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String lineToRemove = "bbb";
String currentLine;

while((currentLine = reader.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(lineToRemove)) continue;
    writer.write(currentLine);
}

boolean successful = tempFile.renameTo(inputFile);
SingleShot
I have found something like this on the internet but anyway thanks a lot!
Narek
You should add a writer.close() before the rename. Otherwise the writer might not have flushed the last line or two to disk.
Steve McLeod
+1  A: 

You want to do something like the following:

  • Open the old file for reading
  • Open a new (temporary) file for writing
  • Iterate over the lines in the old file (probably using a BufferedReader)
    • For each line, check if it matches what you are supposed to remove
    • If it matches, do nothing
    • If it doesn't match, write it to the temporary file
  • When done, close both files
  • Delete the old file
  • Rename the temporary file to the name of the original file

(I won't write the actual code, since this looks like homework, but feel free to post other questions on specific bits that you have trouble with)

Adam Batkin
Now if only you had written out the code too, then you would have got the accepted answer, doh! ;)
DaveJohnston
A: 
public void removeLineFromFile(String file, String lineToRemove) {

try {

  File inFile = new File(file);

  if (!inFile.isFile()) {
    System.out.println("Parameter is not an existing file");
    return;
  }

  //Construct the new file that will later be renamed to the original filename.
  File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

  BufferedReader br = new BufferedReader(new FileReader(file));
  PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

  String line = null;

  //Read from the original file and write to the new
  //unless content matches data to be removed.
  while ((line = br.readLine()) != null) {

    if (!line.trim().equals(lineToRemove)) {

      pw.println(line);
      pw.flush();
    }
  }
  pw.close();
  br.close();

  //Delete the original file
  if (!inFile.delete()) {
    System.out.println("Could not delete file");
    return;
  }

  //Rename the new file to the filename the original file had.
  if (!tempFile.renameTo(inFile))
    System.out.println("Could not rename file");

}
catch (FileNotFoundException ex) {
  ex.printStackTrace();
}
catch (IOException ex) {
  ex.printStackTrace();
}

}

This I have found on the internet.

Narek
This code won't close the files if an exception is thrown, you need a finally statement in there too.
DaveJohnston