Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - 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("
");
                    }
                } finally {
                    writer.close();
                }*/
            } else if (Command.startsWith("EXIT") || Comand.startsWith("exit")) {
                out = true;
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

FileUtils#writeLines seems to do exactly what you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...