classic imperativ works as expected:
static void updateFile(final File pm, final String replace,
final String replacement) {
BufferedReader bri = null;
BufferedWriter out = null;
try {
String fName = pm.getPath() + ".new";
bri = new BufferedReader(new FileReader(pm));
out = new BufferedWriter(new FileWriter(fName));
String line = bri.readLine();
while (line != null) {
if (line.contains(replace)) {
line = line.replace(replace, replacement);
}
out.write(line);
out.newLine();
line = bri.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
bri.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now a try of replacement:
static void updateFileLambda(final File pm, final String replace,
final String replacement) throws Exception {
String fName = pm.getPath() + ".new";
BufferedReader bri = new BufferedReader(new FileReader(pm));
BufferedWriter out = new BufferedWriter(new FileWriter(fName));
bri.lines().filter(ln -> ln.contains(replace))
.map(ln -> ln.replace(replace, replacement))
.forEach(ln -> {
out.write(ln);
out.newLine();
});
}
1.) This raises several problems and doesn't compile because out.write and out.writeLine Eclipse mars is telling me it should be surrounded with try - catch though throws Ecxeption is declared, or the statemens are surrounded with a try-catch as in the classic version.
2.) Each line should be written to the new file. The old and the new should differ only be one modified line. I suspect, the show solution would write the modified line only to the new file.
So if somebody has an idea how to realize correctly, i would very much appreciate!