I am trying to write many lines read from a file to a second file. I am able to loop through lines (sout can print all lines) of text but it's not possible to write all lines in the new file. It writes only the last line.
Any help:
lines.forEach(line -> {
// Append the line separator
String lineToWrite = line; // + System.lineSeparator(); //
// Write every line to the output file
try {
//Files.write(output, lineToWrite.getBytes(StandardCharsets.UTF_8));
//Files.write(output, Collections.singleton(lineToWrite),StandardCharsets.UTF_8);
PrintWriter writer = new PrintWriter(outputdir, "UTF-8");
writer.println(lineToWrite);
System.out.println(lineToWrite);
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("error lines linewrite:"+e);
}
});
PrintWriter writer = new PrintWriter(outputdir, "UTF-8");outside the loop, you are creating a new writer for each line.outputdir?