我目前正在寻找一种创建新文本文件的方法,该文件是使用ArrayList中的值创建的。如何创建文本文件,使其具有所需的格式?
答案 0 :(得分:1)
公共静态无效createTextFileFromArrayList(){
List<String> cities = new ArrayList<String>();
cities.addAll(Arrays.asList("Boston", "Washington", "Irving", "Dallas"));
//Get the file reference
Path path = Paths.get("C:\\apps\\output.txt");
//Use try-with-resource to get auto-closeable writer instance
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
cities.forEach(city -> {
try {
writer.write(city);
writer.write("\n");
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}