Search code examples
javareadfilewritefile

How to read a text file and append a new row with more details in file?


I am reading below text file content and write it to a console using below code.

file content
    
   james;mask;1980
   Mos;josh;1960

how can i append a new line calculating a year from year of birth in a new column

public class Readfile {

    public static void main(String[] args) {
        
        // Create file
        File file = new File("/Users/James/documents/Huber.txt");

        try {
            // Create a buffered reader
            // to read each line from a file.
            BufferedReader in = new BufferedReader(new FileReader(file));
            String ch;
            // Read each line from the file and echo it to the screen.
        
            while ((ch = in.readLine()) != null) {
                
                    System.out.println(ch);

        
            
            }
            
            // Close the buffered reader
            in.close();

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

        } catch (IOException e2) {
            // Catch any other IO exceptions.
            e2.printStackTrace();
        }
    }

}

Solution

  • Assuming that the Date Of Birth doesn't exceed current date.

            StringBuffer inputBuffer = new StringBuffer();
            while ((ch = in.readLine()) != null) {
    
                System.out.println(ch);
                if(ch.split(";").length < 3){ //data unavailable
                    inputBuffer.append(ch).append("\n");
                    continue;
                }
                int year;
                try {  //dob not specified
                    year = Integer.parseInt(ch.split(";")[2]);
                } catch(NumberFormatException e){
                    inputBuffer.append(ch).append(";N/A").append("\n");
                    continue;
                }
                int age = LocalDate.now().getYear() - year;
                inputBuffer.append(ch).append(";").append(age).append("\n");
            }
    
            // Close the buffered reader
            in.close();
            FileOutputStream fileOut = new FileOutputStream(file.getAbsolutePath());
            fileOut.write(inputBuffer.toString().getBytes());
            fileOut.close();