Skip to content
Advertisement

Read from one text file and write into two text files

I need to read from one text file(carsAndBikes.txt) and the write in either cars.txt or bikes.txt carsAndBikes contains a list of cars and bikes and the first character of each name is C or B (C for Car and B for Bike). So far i have that but its showing cars and bikes content. Instead of the separated content.(CARS ONLY OR BIKES ONLY)

   public static void separateCarsAndBikes(String filename) throws FileNotFoundException, IOException
    {
        //complete the body of this method to create two text files
        //cars.txt will contain only cars
        //bikes.txt will contain only bikes    
        
        File fr = new File("C:\Users\KM\Documents\NetBeansProjects\Question4\carsAndBikes.txt");
        Scanner scanFile = new Scanner(fr);                                                             
        String line;
                       
        while(scanFile.hasNextLine())
        {
            line = scanFile.nextLine();
            if(line.startsWith("C"))
            {
               
                try(PrintWriter printWriter = new PrintWriter("C:\Users\KM\Documents\NetBeansProjects\Question4\cars.txt"))
                {                  
                   printWriter.write(line);                                                                           
                }
                catch(Exception e)
                {
                    System.out.println("Message" + e);
                }
            }
            else
            {
                
                try(PrintWriter printWriter = new PrintWriter("C:\Users\KM\Documents\NetBeansProjects\Question4\bikes.txt"))
                {                                       
                    printWriter.write(line);                  
                }
                catch(Exception e)
                {
                    System.out.println("Message" + e);
                }               
            }            
        } 
        //close the file
       scanFile.close();      
    }        

Advertisement

Answer

You’re checking if the input filename starts with a c instead of checking if the line read starts with a c.

You should also open both your output files before your loop, and close them both after the loop.

// Open input file for reading 
File file = new File("C:\Users\KM\Documents\NetBeansProjects\Question4\carsAndBikes.txt");      
BufferedReader br = new BufferedReader(new FileReader(file))); 

// Open bike outputfile for writing
// Open cars outputfile for writing

// loop over input file contents
String line;
while( line = br.readLine()) != null ) {

    // check the start of line for the character
    if (line.startsWith("C") {
        // write to cars
    } else {
        // write to bikes
    }
}

// close all files
Advertisement