Please program to the List
interface. To your question use System.lineSeparator()
, because "\n"
is not cross-platform (on Windows, the line separator is "\r\n"
). Next, File
provides two argument constructors. And there is BufferedWriter.newLine()
which might look like
List<String> list = new ArrayList<>();
File file = new File(dir.getAbsolutePath(), "SavedJavaArithmetic.txt");
try (FileWriter fileW = new FileWriter(file);
BufferedWriter buffW = new BufferedWriter(fileW)) {
for (int i = 0; i < list.size(); i++) {
buffW.write(list.get(i));
buffW.newLine();
}
}
Alternatively, use a PrintWriter
(it provides a more natural syntax). And, I would use a for-each
loop. Also, in both cases, I would use a try-with-resources
to handle the close
(s). Putting that all together might look something like,
List<String> list = new ArrayList<>();
// ...
File file = new File(dir.getAbsolutePath(), "SavedJavaArithmetic.txt");
try (PrintWriter pw = new PrintWriter(file)) {
for (String str : list) {
pw.println(str);
}
}
And, in Java 8+, using a Stream
with a forEachOrdered
like
List<String> list = new ArrayList<>();
File file = new File(dir.getAbsolutePath(), "SavedJavaArithmetic.txt");
try (PrintWriter pw = new PrintWriter(file)) {
list.stream().forEachOrdered(pw::println);
}