Output a list to a file

I have a list that I want to output to a file. Each element in the list should be saved in a new line in the file. I’m able to print the list but when I output it to a file, it’s empty.

UIFileChooser is from this library https://ecs.wgtn.ac.nz/foswiki/pub/Main/JavaResources/UIFileChooser.html

public List <String> myList = new ArrayList<String>();

    public void saveToFile(List<String> myList) {
        String filename = UIFileChooser.save("Filename to save to");
        try {
            PrintStream outfile = new PrintStream(filename);
            for (String line: myList) {
                outfile.println(line);
            }
            outfile.close();
        } catch (IOException e) {UI.println("File failure: " + e);}
    }

Answer

You can find the solution below. Tested and it works.

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

class Main {

    public static void main(String args[]) throws IOException {

        List<String> myList = new ArrayList<String>();
        myList.add("a");
        myList.add("b");
        myList.add("c");
        myList.add("d");
        saveToFile(myList);

    }

    public static void saveToFile(List<String> myList) throws IOException {
        File output = new File("file.txt");
        output.createNewFile();

        PrintStream write = new PrintStream(output);
        for (String line : myList) {
            write.println(line);
        }
        write.close();

    }

}

file.txt output:

a
b
c
d

Change this part:

File output = new File("file.txt");
output.createNewFile();
PrintStream write = new PrintStream(output);

with this line of code if you want to append to already existing file:

PrintStream write = new PrintStream(new FileOutputStream("file.txt", true));