1) Solution for a short file (which fits in memory) with Java 7
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
String line5 = replaceAge(lines.get(4), newAge);
lines.set(4, line5);
Path tmp = Files.createTempFile(prefix, suffix, attrs);
Files.write(path, lines)
Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
2) For a big file
Path tmp = Files.createTempFile(prefix, suffix, attrs);
try (BufferedWriter bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line;
for (int i = 1; (line = br.readLine()) != null; i++) {
if (i == 5) {
line = replaceAge(line, newAge);
}
bw.write(line);
bw.newLine();
}
}
Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);