Gabriel Luna
Gabriel Luna

Reputation: 127

How to remove a line in text file java?

Basically I have this code.. I want to be able to display the delete a line in the text file ..

Example:

Gab 223-2587
Mark 221-5678
Reca 227-7589
Feb 224-8597

Command:

remove Mark

The result in the text file should be:

Gab 223-2587
Reca 227-7589
Feb 224-8597

My problem is, it doesn't remove the line that I want to remove.. and the text file becomes empty.. Or if i add a contact and then attempt to remove an existing contact.. the file will only contain the recently added contact..

Here's my code:

  File inputFile = new File("C:/Users/Gab Real/workspace/CSc121/MyContacts.txt");
    System.out.println(String.format("File.canWrite() says %s", inputFile.canWrite()));

    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    Scanner scan = new Scanner(System.in);
    String word = "";
    String currentline = " ";
    StringBuilder fileOutput = new StringBuilder();

    while((currentline = reader.readLine()) != null) {
        fileOutput.append(currentline + "\r\n");
    }

    PrintWriter out = new PrintWriter(inputFile);
    out.println(fileOutput.toString());


    if(word.startsWith("add")){
        out.append(entries[1] + " " + entries[2] + "\r\n");
        //out.println(out.toString());
        //out.write("\r\n");
    } 
//my if condition to remove a line
    else if (word.contains("remove")){
            String currentLine;
            while((currentLine = reader.readLine()) != null) {
                // trim newline when comparing with lineToRemove
                String trimmedLine = currentLine.trim();
                if(trimmedLine.contains(entries[1])) continue;
                out.append(currentLine + System.getProperty("line.separator")); 
            }

Upvotes: 0

Views: 832

Answers (3)

9000
9000

Reputation: 40894

Your program conflates several concerns. Try to separate them.

public static void main(String[] args) {
  ...
  String command = ...; // take it from args somehow
  String marker = ...; 
  ...
  if ('remove'.equals(command)) removeLine(marker);
  else if...
  ...
}

void removeLine(marker) {
  // open files as you already do
  while((currentline = reader.readLine()) != null) {
     if (currentLine.indexOf(marker) < 0) {
       output.writeln(currentLine);
     } // else the line is skipped
  }
  // close files
}

Upvotes: 0

Dima
Dima

Reputation: 40510

You cannot read and write the same file at the same time. Either read everything into memory first, before creating PrintWriter or write to a different file (and then, possibly, copy it over to the original after you are done).

Also, be sure to .close() your writer after you are done writing to it.

Oh, and, yes, you cannot read from the same reader twice. If you want to start reading from the beginning, create a new reader.

Upvotes: 1

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77495

PrintWriter out = new PrintWriter(inputFile);

AAARGH. Please, never name an output file inputFile...

enter image description here

Also, don't hardcode DOS linewraps "\r\n". This makes your program non-portable.

Other than that, your program logic is just completely busted...

You already read all lines in the first

while((currentline = reader.readLine()) != null) {

Your second attempt at filtering the lines thus fails, because you are already at the end of the file, from your first read above.

Two solutions:

  1. Don't read the file until you need to, or reread it every time.

  2. Read it only once into a modifiable data structure, such as LinkedList<String>. Do all the modifications; then write it out in the end, once.

Upvotes: 2

Related Questions