1

How can I remove or trim a line in a text file in Java? This is my program but it does not work. I want to remove a line in text file, a line contain the word of user input

  try {
        File inputFile = new File("temp.txt");
        File tempFile = new File("temp1.txt");

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

        String lineToRemove = name;
        String currentLine;

        while((currentLine = reader.readLine()) != null)
        {
            //trim newline when comparing with lineToRemove
            String trimmedLine = currentLine.trim();
            if(!trimmedLine.startsWith(lineToRemove))
            {
                // if current line not start with lineToRemove then write to file
                writer.write(currentLine);
            }
        }
        writer.close();
        reader.close();
    }
    catch(IOException ex)
    {
        System.out.println("Error reading to file '" + fileName + "'");

    }
RustyTheBoyRobot
  • 5,670
  • 4
  • 33
  • 53

2 Answers2

1

You are not separating the lines with a line break character, so the resulting file will have one single long line. One possible way to fix that is just writing the line separator after each line.

Another possible problem is that you are only checking if the current line starts with the given string. If you want to check if the line contains the string you should use the contains method.

A third problem is that you are not writing the trimmed line, but the line as it is. You really don't say what you expect from the program, but if you are supposed to output trimmed lines it should look like this:

        if(!trimmedLine.contains(lineToRemove)) {
            writer.write(trimmedLine);
            writer.newLine();
        }
Joni
  • 101,441
  • 12
  • 123
  • 178
0

startsWith() is the culprit. You are checking if the line starts with "lineToRemove". As @Joni suggested use contains.

SarZ
  • 206
  • 2
  • 8