【问题标题】:Java - How to write ArrayList Objects into txt file?Java - 如何将 ArrayList 对象写入 txt 文件?
【发布时间】:2013-10-04 15:19:33
【问题描述】:

/** 我有一些方法,如添加、显示、排序、删除和退出,它们实现了 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;
            }
        }
    }
}

【问题讨论】:

  • 请先修复代码格式!您应该遵守 Java 编码准则(例如,变量的小写字母等)!
  • 你不应该问same question twice
  • 是的,下次不会再这样了。

标签: java arrays serialization arraylist


【解决方案1】:

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

【讨论】:

  • tq 回答问题,但我真的没有太多时间阅读手册。
  • @user2826017 这是一个完整的答案,无需阅读任何手册。下载 apache jar,将其导入您的项目,然后使用 FileUtils.writeLines(new File("input.txt"), MenuArray);
  • 好的,我会试试的……我前几天自己学了Java,现在正在做这个任务……所以我没有的东西太多了真的不明白。
  • 不过,如果我们帮助 OP 解决他最初的问题会更好 - 为什么他不能使用 Writer 和循环来解决?
【解决方案2】:

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

【讨论】:

  • 我尝试了代码,它可以工作并创建 ouput.txt,但这是文件中的内容:¬í sr java.util.ArrayListxÒ™Ça I sizexp wt hellox // 我刚刚输入了单词“你好”
  • 老兄,那我怎样才能显示文件中的对象呢?这是下一个方法: else if(Command.startsWith("DISPLAY") || Command.startsWith("display") ) { int i=0; for(String temp: MenuArray){ System.out.println(++i + "." + temp); }
  • @lawZ:您使用ObjectInputStream 读取文件,请参阅示例代码http://www.tutorialspoint.com/java/io/objectinputstream_readobject.htm
  • @lawZ:我看到了你的相关问题。你想让我在那里发表同样的回复吗?
猜你喜欢
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2018-08-09
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
相关资源
最近更新 更多