How do i append an existing line in a text file? What if the line to be edited is in the middle of the file? Please kindly offer a suggestion, given the following code.
Have went through & tried the following:
- How to add a new line of text to an existing file in Java?
- How to append existing line within a java text file
My code:
    filePath = new File("").getAbsolutePath();
    BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
    try
    {                           
        String line = null;         
        while ((line = reader.readLine()) != null)
        {
            if (!(line.startsWith("*")))
            {
                //System.out.println(line);
                //check if target customer exists, via 2 fields - customer name, contact number
                if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
                {
                    System.out.println ("\nWelcome (Existing User) " + line + "!");
                    //w target customer, alter total number of bookings @ 5th line of 'Customer.txt', by reading lines sequentially
                    reader.readLine();
                    reader.readLine();
                    int total_no_of_bookings = Integer.valueOf(reader.readLine());
                    System.out.println (total_no_of_bookings);
                    reader.close();
                    valid = true;
                    //append total number of bookings (5th line) of target customer @ 'Customer.txt'
                    try {
                        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
                        writer.write(total_no_of_bookings + 1);
                        //writer.write("\n");
                        writer.close();
                    }
                    catch (IOException ex) 
                    {
                        ex.printStackTrace();
                    } 
                    //finally 
                   // {
                        //writer.close();
                    //}
                }                   
            }
        }       
 
     
     
     
     
    