First you have the list
List sample = new ArrayList<>();
sample.add("foo");
sample.add("bar");
sample.add("bizz");
sample.add("bazz");
Then we define a BufferWriter with a FileWriter pointing to where the file will be
BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"));
Then we do some streams and forEach to write the file.
sample.stream().forEach(s -> {
System.out.println(s);
try {
writer.write(s + '\n');
} catch (IOException e) {
e.printStackTrace();
}
});
And finally we close the buffer as good citizens.
writer.close();
All together now:
package com.sourcecodecenter;
import java.util.*;
import java.io.*;
public class ListToFile {
public static void main(String []args) throws Exception {
List sample = new ArrayList<>();
sample.add("foo");
sample.add("bar");
sample.add("bizz");
sample.add("bazz");
BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"));
sample.stream().forEach(s -> {
System.out.println(s);
try {
writer.write(s + '\n');
} catch (IOException e) {
e.printStackTrace();
}
});
writer.close();
}
}
No hay comentarios:
Publicar un comentario