Java - 如何将 ArrayList 对象写入 txt 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19065797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:49:27  来源:igfitidea点击:

Java - How to write ArrayList Objects into txt file?

javaarraysserializationarraylist

提问by lawZ

/** I have some methods likes add,display,sort,delete,and exit that implemented the ArrayList function. It works correctly, but the problem is that the objects that had been added were not saved on a .txt file, just the temporary objects. So I need to add them into text file,so that I can display and delete them later. Here's the part of the codes. */

/** 我有一些方法,比如添加、显示、排序、删除和退出,实现了 ArrayList 函数。它工作正常,但问题是添加的对象没有保存在 .txt 文件中,只是临时对象。所以我需要将它们添加到文本文件中,以便稍后显示和删除它们。这是代码的一部分。*/

public class testing {

    public static void main(String[] args) {
        String Command;
        int index = 0;
        Scanner input = new Scanner(System.in);
        ArrayList<String> MenuArray = new ArrayList<String>();
        boolean out = false;
        while (!out) {
            System.out.print("Enter your Command: ");
            Command = input.nextLine();
            // method ADD for adding object
            if (Command.startsWith("ADD ") || Command.startsWith("add ")) {
                MenuArray.add(Command.substring(4).toLowerCase());
                // indexing the object
                index++;
                /** i stuck here,it won't written into input.txt 
                BufferedWriter writer = new BufferedWriter(new FileWriter(
                        "input.txt"));
                try {
                    for (String save : MenuArray) {
                        int i = 0;
                        writer.write(++i + ". " + save.toString());
                        writer.write("\n");
                    }
                } finally {
                    writer.close();
                }*/
            } else if (Command.startsWith("EXIT") || Comand.startsWith("exit")) {
                out = true;
            }
        }
    }
}

采纳答案by anubhava

You can use ObjectOutputStreamto write an object into a file:

您可以使用ObjectOutputStream将对象写入文件:

try {
    FileOutputStream fos = new FileOutputStream("output");
    ObjectOutputStream oos = new ObjectOutputStream(fos);   
    oos.writeObject(MenuArray); // write MenuArray to ObjectOutputStream
    oos.close(); 
} catch(Exception ex) {
    ex.printStackTrace();
}

回答by sp00m

FileUtils#writeLinesseems to do exactly what you need.

FileUtils#writeLines似乎正是您所需要的。