2013-09-28 45 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