Reputation: 79
I have tried using writer.newLine()
however it says method not found. Does anyone know how I can write a new line after each iteration?
public static void keepLetters() throws IOException {
BufferedReader sourceReader = new BufferedReader(new FileReader("input.txt"));
for (String line = sourceReader.readLine(); line != null; line = sourceReader.readLine()) {
String updatedLine = line.replaceAll("[^A-Za-z]", "");
System.out.println(updatedLine);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("output.txt"), "UTF-8"))) {
writer.write(updatedLine);
}
}
}
I wrote writer.nextLine()
after writer.write(updatedLine)
;
Thank you
Upvotes: 1
Views: 5702
Reputation: 6307
The correct method is newLine()
, but you need to call it on a BufferedWriter
, not a Writer
.
Like so:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("output.txt", true), "UTF-8"))) {
writer.write(updatedLine);
writer.newLine();
}
Note this part try (BufferedWriter writer
Update for comment
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8"));
for (int i = 0; i < linesToWrite; i++){
writer.write(updatedLine);
writer.newLine();
}
writer.close();
Upvotes: 3
Reputation: 1696
You can simple do
writer.write(updatedLine + "\n");
which will ensure a newline is written after every updatedLine.
EDIT:
The writer is being reinitiated to the same file output every iteration of the loop. It should be initialised once before the loop and closed later on to resolve your issue.
Upvotes: 0