How can you write a list collection to a file in Java?

In Java, you can use the FileWriter or BufferedWriter class to write a List collection to a file. Here is an example code:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class WriteListToFile {
    public static void main(String[] args) {
        List<String> list = List.of("apple", "banana", "orange");

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            for (String item : list) {
                writer.write(item);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we created a List collection containing three fruits and then wrote these fruits to a file named “output.txt”. By using the BufferedWriter class, we were able to write the contents of the List collection to the file line by line. If the file does not exist, a new file will be created and the data will be written to it. If the file already exists, the original content will be overwritten.

bannerAds