2010-04-17 58 views
3

這很簡單我知道,但我沒有互聯網訪問和netcafes鍵盤糟透了,所以如果有人可以回答這個問題,請。寫入和讀取文件中的ArrayList對象

這是什麼課程?給我一個正確的方向。有一個簡單的ArrayList對象,我想寫入和從文件讀取。 謝謝

回答

4

這個問題沒有單一的明確答案。這取決於文件的格式和列表中的對象。你需要一個序列化器。例如,您可以使用BinaryFormatter將對象實例序列化爲二進制文件,但對象必須是serializable。另一種選擇是使用XML格式的。


UPDATE:

下面是用BinaryFormatter的一個例子:

class Program 
{ 
    static void Main() 
    { 
     var list = new ArrayList(); 
     list.Add("item1"); 
     list.Add("item2"); 

     // Serialize the list to a file 
     var serializer = new BinaryFormatter(); 
     using (var stream = File.OpenWrite("test.dat")) 
     { 
      serializer.Serialize(stream, list); 
     } 

     // Deserialize the list from a file 
     using (var stream = File.OpenRead("test.dat")) 
     { 
      list = (ArrayList)serializer.Deserialize(stream); 
     } 
    } 
} 
+0

我想他也給了一個很好的答案。你現在應該可以研究BinaryFormatter類。 – Nayan 2010-04-17 10:17:30

1

因爲你沒有提到這個數組包含什麼類型的數據,我建議寫在二進制格式的文件。

Here is a good tutorial on how to read and write in binary format.

基本上,你需要使用BinaryReaderBinaryWriter類。

[編輯]

private static void write() 
    { 
     List<string> list = new List<string>(); 
     list.Add("ab"); 
     list.Add("db"); 
     Stream stream = new FileStream("D:\\Bar.dat", FileMode.Create); 
     BinaryWriter binWriter = new BinaryWriter(stream); 
     binWriter.Write(list.Count); 
     foreach (string _string in list) 
     { 
      binWriter.Write(_string); 
     } 
     binWriter.Close(); 
     stream.Close(); 
    } 

    private static void read() 
    { 
     List<string> list = new List<string>(); 
     Stream stream = new FileStream("D:\\Bar.dat", FileMode.Open); 
     BinaryReader binReader = new BinaryReader(stream); 

     int pos = 0; 
     int length = binReader.ReadInt32(); 
     while (pos < length) 
     { 
      list.Add(binReader.ReadString()); 
      pos ++; 
     } 
     binReader.Close(); 
     stream.Close(); 
    } 
+0

我不確定,但是從我記得的東西中,binarywriter的write方法不寫集合對象,只有原始類型。所以沒有使用脯氨酸 – user257412 2010-04-17 10:15:07

+0

真的嗎?你以前用過這些課嗎?看到我編輯的答案。 – Nayan 2010-04-17 10:18:27

0

如果ArrayList中的對象序列化,你可以選擇二進制序列化。但這意味着任何其他應用程序都需要知道序列化,然後才能使用這些文件。您可能想澄清您使用序列化的意圖。所以問題仍然存在,爲什麼你需要做一個序列化?如果它很簡單,爲了你自己(這個應用程序的)使用,你可以考慮二進制序列化。可以肯定,你的對象是可序列化的。否則,您需要考慮XML序列化。

二進制序列化,你能想到的一些像這樣的代碼:

Stream stream = File.Open("C:\\mySerializedData.Net", FileMode.Create); 
BinaryFormatter bformatter = new BinaryFormatter(); 
bformatter.Serialize(stream, myArray); 
stream.Close(); 
+0

我得到了幾個可以接受的答案,謝謝大家 – user257412 2010-04-18 07:28:54