将列表输出到文件

Output a list to a file

我有一个要输出到文件的列表。列表中的每个元素都应保存在文件中的新行中。我可以打印列表,但是当我将它输出到文件时,它是空的。

UIFileChooser 来自本库 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);}
    }

您可以在下面找到解决方案。已测试,有效。

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 输出:

a
b
c
d

更改此部分:

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

如果要附加到现有文件,请使用这行代码:

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