-8
  • I want the text file to be in a particular format which is really what I am getting at.

I am currently looking for a way to create a new text file that is created by using the values from an ArrayList. How do I create a text file that will allow me to have the format that I am looking for?

Eli
  • 55
  • 9

1 Answers1

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();
    }
}