如何读取文本文件并在文件中附加一个包含更多详细信息的新行?

问题描述

我正在阅读下面的文本文件内容,并使用下面的代码将其写入控制台。

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

我如何在新列中添加新行来计算从出生年份开始的年份

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();
        }
    }

}

解决方法

假定出生日期不超过当前日期。

        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();