lawZ
lawZ

Reputation: 39

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

Upvotes: 2

Views: 46022

Answers (2)

sp00m
sp00m

Reputation: 48807

FileUtils#writeLines seems to do exactly what you need.

Upvotes: 4

anubhava
anubhava

Reputation: 784898

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

Upvotes: 3

Related Questions