使用ArrayList中的值创建新文本文件的最简单方法是什么? [关闭]

问题描述 投票:-8回答:1
  • 我希望文本文件采用特定格式,这正是我所得到的。

我目前正在寻找一种方法来创建一个使用ArrayList中的值创建的新文本文件。如何创建一个允许我使用我正在寻找的格式的文本文件?

java arraylist fileinputstream
1个回答
1
投票

public static void 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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.