Search code examples
javafilereadertxtbufferedwriter

how to select data in txt file and print into different txt file java


I have a txt file called employees.txt which contain employee id and names. Their id starts with either 18,19 or 20. And have to look within the file if the line starts with 18 it needs to go to another txt file employee18.txt if starts with 19 then go to employee19.txt and the same way if it starts with 20 goes to employee20.txt.I share my code for what I have done so far. I have been able to read the file and also by using Scanner looks for line which starts with 18,19or 20. The problem is when I run the code it shows all the values to the console but adds only one last value within the employee.txt file to employee18.txt or employee19.txt and employee20.txt.What I am doing wrong I don't know entries in employees.txt are

1801234 IMRAN KHAN
1801235 ANDREW FLINTOFF
1905001 SACHIN TICKHULE
1905002 VIRAT KOHLI
2006001 KATY SPENCER
2006002 RANDOM MAN

After running code

    1801234 IMRAN KHAN
    1801235 ANDREW FLINTOFF

should appear in employee18.txt and

    1905001 SACHIN TICKHULE
    1905002 VIRAT KOHLI

should appear in employee19.txt.However, when I run code it only adds 1801235 ANDREW FLINTOFF and 1905002 VIRAT KOHLI to the said files. Here is what I have done so far

package separatingEmployees;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;




public class SeparateEmployees {

public static void main(String[] args)  {
    
    try {
        File file = new File("employees.txt");
        Scanner s= new Scanner(file);
        
        while(s.hasNext()){
            String st=s.nextLine();
            if(st.startsWith("18")){//LOOK FOR LINE START WITH 18 
                 try {
            BufferedWriter w=new BufferedWriter(new FileWriter("employees18.txt"));
            w.write(st);
               // System.out.println("file created");
            w.close();
             } catch (IOException ex) {
               System.out.println("cant write");
             }
               System.out.println(st);
            }if(st.startsWith("19")){//LOOK FOR LINE START WITH 19
                 try {
            BufferedWriter w=new BufferedWriter(new FileWriter("employees19.txt"));
            w.write(st);
               // System.out.println("file created");
            w.close();
             } catch (IOException ex) {
               System.out.println("cant write");
             }
               System.out.println(st);
            }if(st.startsWith("20")){ // LOOK FOR LINE STARTS WITH 20 AND SEND TO EMPLOYEES20.TXT
                 try {
            BufferedWriter w=new BufferedWriter(new FileWriter("employees20.txt"));
            w.write(st);
               // System.out.println("file created");
            w.close();
             } catch (IOException ex) {
               System.out.println("cant write");
             }
               System.out.println(st);
            }
            }
            } catch (FileNotFoundException ex) {
             System.out.println("catch block"); 
        
            }finally {
            System.out.println("finally block");
            //write();
            
            
        }
        }
   


    }


enter code here

Solution

  • The problem is that you are creating the file for every new line you want to add (which seems a bit inefficient). One approach is to open the file on append mode so lines will be add to the existing content (new FileWriter(filename, true)). But I think a better approach will be to open the files to write before iterating and closing them at the end:

    // Open the files before iterating:
    BufferedWriter w19=new BufferedWriter(new FileWriter("employees19.txt"));
    BufferedWriter w18=new BufferedWriter(new FileWriter("employees18.txt"));
    BufferedWriter w20=new BufferedWriter(new FileWriter("employees20.txt"));
    while(s.hasNext()){
        String st=s.nextLine();
        if(st.startsWith("18")){//LOOK FOR LINE START WITH 18 
            w18.write(st);
            System.out.println(st);
        } if (st.startsWith("19")){//LOOK FOR LINE START WITH 19
            w19.write(st);
            System.out.println(st);
        }if(st.startsWith("20")){ // LOOK FOR LINE STARTS WITH 20 AND SEND TO EMPLOYEES20.TXT
            w20.write(st);
        }
    

    after processing close the files created:

    w20.close()
    w19.close()
    w18.close()
    

    Add the Exception treatment where you consider it better.