简体   繁体   中英

Java - How to write ArrayList Objects into txt file?

/** 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. */

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;
            }
        }
    }
}

FileUtils#writeLines似乎完全符合您的需求。

You can use ObjectOutputStream to write an object into a file:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM