4

I want to delete a specific line from a text file. I found that line, but what to do next? Any idea?

6 Answers 6

5

Read file from stream and write it to another stream and skip the line which you want to delete

Sign up to request clarification or add additional context in comments.

Comments

5

There is no magic to removing lines.

  • Copy the file line by line, without the line you don't want.
  • Delete the original file.
  • rename the copy as the original file.

1 Comment

You make a new file by writing to a file which doesn't exist. You can append an extension like .new to create a new file. You can rename it with File.rename()
4

Try this code.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


class Solution {
    public static void main(String[] args) throws FileNotFoundException, IOException{

        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 + System.getProperty("line.separator"));
        }
        writer.close(); 
        reader.close(); 
        boolean successful = tempFile.renameTo(inputFile);
        System.out.println(successful);

    }
}

Comments

2

Try to read file:

 public static String readAllText(String filename) throws Exception {
    StringBuilder sb = new StringBuilder();
    Files.lines(Paths.get(filename)).forEach(sb::append);
    return sb.toString();
}

then split text from specific character (for new line "\n")

private String changeFile(){
String file = readAllText("file1.txt"); 
String[] arr = file.split("\n"); // every arr items is a line now.
StringBuilder sb = new StringBuilder();
for(String s : arr)
{
   if(s.contains("characterfromlinewillbedeleted"))
   continue;
   sb.append(s); //If you want to split with new lines you can use sb.append(s + "\n");
}
return sb.toString(); //new file that does not contains that lines.
}

then write this file's string to new file with:

public static void writeAllText(String text, String fileout) {
    try {
        PrintWriter pw = new PrintWriter(fileout);
        pw.print(text);
        pw.close();
    } catch (Exception e) {
        //handle exception here
    }
}


writeAllText(changeFile(),"newfilename.txt");

1 Comment

You should change here "characterfromlinewillbedeleted" to what you lines will be deleted have.
1

Deleting a text line directly in a file is not possible. We have to read the file into memory, remove the text line and rewrite the edited content.

2 Comments

Although, of course, it isn't necessary that the entire file fits into memory, as you can read and write in the same loop.
@Simon - agreed - we don't have to store the entire file in memory but, at the end, every single byte of the file has been read, buffered somewhere in the RAM and written to the new target file.
0

Maybe a search method would do what you want i.e. "search" method takes a string as a parameter and search for it into the file and replace the line contains that string.

PS:

public static void search (String s)
{
    String buffer = "";
    try {

        Scanner scan = new Scanner (new File ("filename.txt"));
        while (scan.hasNext())
        {
            buffer = scan.nextLine();

            String [] splittedLine = buffer.split(" ");
            if (splittedLine[0].equals(s))
            {

                buffer = "";

            }
            else
            {
                //print some message that tells you that the string not found


            }
        }
        scan.close();

    } catch (FileNotFoundException e) {
        System.out.println("An error occured while searching in file!");
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.