Home » Java » java – Deleting an element from a text file-Exceptionshub

java – Deleting an element from a text file-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have created a text file named ‘Month.txt’ which contains this String: “January February March”.
This is my program below which deletes “February” from the text file:

import java.io.*;
import java.util.*;

class Delete_element_from_txtfile
{
    public static void main()throws IOException
    {
        FileReader fr=new FileReader("Month.txt");
        BufferedReader br=new BufferedReader(fr);

        FileWriter fw=new FileWriter("Month.txt");
        BufferedWriter bw=new BufferedWriter(fw);
        PrintWriter pw=new PrintWriter(bw);

        String str;
        String newstr="";

        while((str=br.readLine())!=null)
        {
            StringTokenizer S=new StringTokenizer(str);
            while(S.hasMoreTokens()==true)
            {
                String month=S.nextToken();
                if(month.equals("February"))
                {
                    continue;
                }
                else
                    newstr=newstr+(month+" ");
            }
        }
        pw.print(newstr);

        pw.close();
        bw.close();
        fw.close();

        br.close();
        fr.close();
    }
}

However after running the program, when I open the file, it’s all empty. I have just started file handling in java, so I have no clue of what’s going on. I would like some help on this problem. Thanks!

How to&Answers:

You are opening Same file for reading and writing is the issue. Because you are opening file for write immediately after reading and hence it is overwriting the current data.

Just move the Writing code after file reader is closed.

Here is updated code:

public static void main(String []ars)throws IOException
    {
        FileReader fr=new FileReader("Month.txt");
        BufferedReader br=new BufferedReader(fr);


        String str;
        String newstr="";

        while((str=br.readLine())!=null)
        {
            StringTokenizer S=new StringTokenizer(str);
            while(S.hasMoreTokens()==true)
            {
                String month=S.nextToken();
                if(month.equals("February"))
                {
                    continue;
                }
                else
                    newstr=newstr+(month+" ");
            }
        }


        br.close();
        fr.close();

        FileWriter fw=new FileWriter("Month.txt");
        BufferedWriter bw=new BufferedWriter(fw);
        PrintWriter pw=new PrintWriter(bw);
        pw.print(newstr);

        pw.close();
        bw.close();
        fw.close();

    }

Answer:

Here is a much more compact and nicer looking solution:

List<String> lines = Files.readAllLines(Paths.get("Month.txt")); //read every line
//filer out lines that contain february
lines = lines.stream().filer(line -> !line.contains("February")).collect(Collectors.toList());
Files.write(Paths.get("Month.txt"), lines, Charset.defaultCharset()); //write it back

No need to close file reading streams manually, no need to use while loops, and classes like StringTokenizer!