在文件指定行插入一段内容

public class Main {
    public static void main(String[] args){
        try {
            File file1 = new File("src/main/resources/test.txt");
            File file2 = new File("src/main/resources/tmp.txt");
            BufferedReader br = new BufferedReader(new FileReader(file1));
            BufferedWriter bw = new BufferedWriter(new FileWriter(file2));
            String line;
            int i = 0;
            while ((line = br.readLine()) != null){
                i++;
                if(i != 1){
                    bw.newLine();
                }
                bw.write(line);
                if (i == 4){
                    bw.newLine();
                    bw.write("haha");
                }
            }
            bw.flush();
            bw.close();

            file2.renameTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(在文件指定行插入一段内容)