2012-10-23 64 views
1

閱讀HashMap中我發現的代碼讀取一個HashMap從文件(在磁盤上):如何從文件

public HashMap<String, Integer> load(String path) 
{ 
    try 
    { 
     ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path)); 
     Object result = ois.readObject(); 
     //you can feel free to cast result to HashMap<String, Integer> if you know that only a HashMap is stored in the file 
     return (HashMap<String, Integer>)result; 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

,但我沒有發現任何例如如何這個文件看起來像。你能用一個例子來解釋嗎?

+0

這個文件不會是人類可讀的,因爲這將是二進制格式。 – Apurv

+0

hm是否還有一些其他選項如何從文件 – hudi

+0

中讀取hashMap您需要舉例說明您嘗試從中讀取散列表的文件的格式。 –

回答

4

您需要使用ObjectOutputStream來寫出它(請參閱文檔here)。

+0

@傑夫福斯特 - 尼斯。 –

0

有問題的文件不過是一個序列化的HashMap。

如果你想看看它,首先選擇一個HashMap並找出它。

要Serailizes,你可以用下面的代碼:

HashMap<String,Integer> aHashMap = new HashMap<String,Integer>(); 
aHaspMap.put("one",1); 
aHaspMap.put("two",2); 
aHaspMap.put("three",3); 

File file = new File("serialized_hashmap"); 
FileOutputStream fos = new FileOutputStream(file); 
ObjectOutputStream oos = new ObjectOutputStream(fos);   
oos.writeObject(aHashMap); 
oos.flush(); 

現在,這file您可以根據您提供的程序中使用。

-1

本示例使用Serialization,一種將其狀態轉換爲字節流的技術,以便字節流可以恢復爲對象的副本。

因此,建立這樣一個文件的方式將是序列化HashMap<String, Integer>第一,像這樣:

public void serializeHashMap(HashMap<String, Integer> m) { 
    FileOutputStream fos = new FileOutputStream("hashmap.dat"); 
    ObjectOutputStream oos = new ObjectOutputStream(fos); 

    oos.writeObject(m); 
    oos.close(); 
} 

(這不包括異常處理之類的東西,但你的想法... )

0

這是序列化對象

import java.io.*; 
    public class SerializationDemo { 
    public static void main(String args[]) { 
    // Object serialization 
    try { 
    MyClass object1 = new MyClass("Hello", -7, 2.7e10); 
    System.out.println("object1: " + object1); 
    FileOutputStream fos = new FileOutputStream("serial"); 
    ObjectOutputStream oos = new ObjectOutputStream(fos); 
    oos.writeObject(object1); 
    oos.flush(); 
    oos.close(); 
    } 
    catch(Exception e) { 
    System.out.println("Exception during serialization: " + e); 
    System.exit(0); 
    } 
} 
當然

的典型問題MyClass的應該實現Serializable接口

class MyClass implements Serializable { 
String s; 
int i; 
double d; 
public MyClass(String s, int i, double d) { 
this.s = s; 
this.i = i; 
this.d = d; 
} 
public String toString() { 
return "s=" + s + "; i=" + i + "; d=" + d; 
} 
} 

做到這一點,請參閱文件