If we consider that the file can be very large, I got the following solution:
Path input = Paths.get(fileName); Path output = Files.createTempFile(input.getFileName().toString(), "$1"); try (BufferedWriter br = Files.newBufferedWriter(output)) { Files .lines(input) .map(str -> { if (line.equalsIgnoreCase(str)) return str + System.lineSeparator() + text; else return str; }) .forEach(str -> { try { br.write(str); br.newLine(); } catch (IOException e) { e.printStackTrace(); } }); } Files.move(output, input, StandardCopyOption.REPLACE_EXISTING);