venk
venk

Reputation: 65

How to remove a particular string in a text file using java?

My input file has numerous records and for sample, let us say it has (here line numbers are just for your reference)

 1. end 
 2. endline
 3. endofstory

I expect my output as:

 1. 
 2. endline
 3. endofstory

But when I use this code:

import java.io.*;
public class DeleteTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
        File file = new File("D:/mypath/file.txt");
        File temp = File.createTempFile("file1", ".txt", file.getParentFile());
        String charset = "UTF-8";
        String delete = "end";
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
        for (String line; (line = reader.readLine()) != null;) {
            line = line.replace(delete, "");
            writer.println(line);
        }
        reader.close();
        writer.close();
        }
        catch (Exception e) {
            System.out.println("Something went Wrong");
        }
    }

}

I get my output as:

 1. 
 2. line
 3. ofstory

Can you guys help me out with what I expect as output?

Upvotes: 2

Views: 2397

Answers (1)

Titus
Titus

Reputation: 22474

First, you'll need to replace the line with the new string List item not an empty string. You can do that using line = line.replace(delete, "List item"); but since you want to replace end only when it is the only string on a line you'll have to use something like this:

line = line.replaceAll("^"+delete+"$", "List item");

Based on your edits it seems that you indeed what to replace the line that contains end with an empty string. You can do that using something like this:

line = line.replaceAll("^"+delete+"$", "");

Here, the first parameter of replaceAll is a regular expression, ^ means the start of the string and $ the end. This will replace end only if it is the only thing on that line.

You can also check if the current line is the line you want to delete and just write an empty line to the file.

Eg:

if(line.equals(delete)){
     writer.println();
}else{
     writer.println(line);
}

And to do this process for multiple strings you can use something like this:

Set<String> toDelete = new HashSet<>();
toDelete.add("end");
toDelete.add("something");
toDelete.add("another thing");

if(toDelete.contains(line)){
     writer.println();
}else{
     writer.println(line);
}

Here I'm using a set of strings I want to delete and then check if the current line is one of those strings.

Upvotes: 1

Related Questions