tomtom
tomtom

Reputation: 614

How can i remove a particular text from a file in java?

I have tried to implement a simple program to delete a particular text from a file, some how it is not able to delete it. I am reading entire file content into a temp file , delete the user input string from it and update the content to the original file. Any help would be highly appreciated.

public class TextEraser{

        public static void main(String[] args) throws IOException  {
            
            
            System.out.print("Enter a string to remove  : ");
            Scanner scanner = new Scanner(System. in);
            String inputString = scanner. nextLine();
            
            // Locate the  file
            File file = new File("/Users/lobsang/documents/input.txt");
            
            //create temporary file 
            
            File temp = File.createTempFile("file", ".txt", file.getParentFile());

            String charset = "UTF-8";
            
            

            try {
                
                // Create a buffered reader
                // to read each line from a file.
                BufferedReader in = new BufferedReader(new FileReader(file));
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));

                String s = in.readLine();

                // Read each line from the file and echo it to the screen.
                while (s !=null) {
                    
                          s=s.replace(inputString,"");
                          s = in.readLine();

                }
                

                writer.println(s);
                
                // Close the buffered reader
                in.close();
                writer.close();
                
                file.delete();
                temp.renameTo(file);
                


            } catch (FileNotFoundException e1) {
                // If this file does not exist
                System.err.println("File not found: " + file);

            
        }

    }

Upvotes: 0

Views: 70

Answers (1)

Shubham Pathak
Shubham Pathak

Reputation: 155

After replace with input string, write string immediate in file.

while (s != null) {
    s = s.replace(inputString, "");
    writer.write(s);
    // writer.newLine();
    s = in.readLine();
}

For new line , use BufferedWriter in place of PrintWriter, it contains method newLine()

writer.newLine();

Remove this

writer.println(s);

Upvotes: 1

Related Questions