2013-09-28 284 views
3

/**我有一些方法添加喜欢,显示,排序,删除,并实施了ArrayList的函数退出。它工作正常,但问题是已添加的对象未保存在.txt文件中,只是临时对象。所以我需要将它们添加到文本文件中,以便稍后显示和删除它们。这是代码的一部分。 */Java - 如何将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; 
      } 
     } 
    } 
} 
+2

请修正代码首先格式化!您应该遵守Java编码准则(例如变量的小写字母等)! – isnot2bad

+0

对不起,只是一个新手 – lawZ

+0

你不应该问[同样的问题两次(http://stackoverflow.com/q/19066952/697630) –

回答

3

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

我试过的代码,它的工作原理并创建ouput.txt,但是这是什么里面的文件:¬íSRjava.util.ArrayListxÒ™CA我sizexpW¯¯ 牛逼hellox //我刚刚输入的字“你好” – lawZ

+0

伙计,那我该如何显示文件内的对象?这里是下一个方法:否则如果(Command.startsWith( “DISPLAY”)|| Command.startsWith( “显示”)) \t \t \t {\t \t \t \t \t INT I = 0; \t \t \t为(字符串温度:MenuArray){ \t \t \t \t的System.out.println( “” ++ I + +温度); \t \t \t} – lawZ

+0

@lawZ:使用'ObjectInputStream'看到一个示例代码读取文件'的http:// www.tutorialspoint.com/JAVA/IO/objectinputstream_readobject.htm' – anubhava

4

FileUtils#writeLines似乎做正是你需要的。

+0

tq为回答任务,但我没有太多时间阅读手册。 – lawZ

+1

@ user2826017这是一个完整的答案,不需要阅读任何手册。下载apache jar,将它导入到项目中,并使用'FileUtils.writeLines(new File(“input.txt”),MenuArray);'。 –

+0

好吧,我试试吧...我刚学Java的约数天前我ownself,现在做这个任务......所以有这么多的东西,我真的不明白这一点。 – lawZ