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

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

public class testing { public static void main(String[] args) { String Command; int index = 0; Scanner input = new Scanner(System.in); ArrayList MenuArray = new ArrayList(); 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; } } } } 

您可以使用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(); } 

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