You can use a
PrintWriter
to do this. Note that the following example will overwrite the file if it already exists. If you don't want this, you can use
new File("path/to/file.txt").isFile()
to check if a file already exists.
import java.io.PrintWriter;
public static void printArrayListToFile(ArrayList<String> arrayList, String filename) throws IOException {
PrintWriter writer = new PrintWriter(filename);
for (String line : arrayList) {
writer.println(line);
}
writer.close();
}
You can call this method in your main method like this:
printArrayListToFile(elements, "output.txt");