如何从文件中读取hashMap

时间:2012-10-23 11:06:25

标签: java 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();
    }
}

但我没有找到任何示例这个文件是怎么样的。你能借助一个例子来解释这个吗?

4 个答案:

答案 0 :(得分:4)

您需要使用ObjectOutputStream将其写出来(请参阅文档here)。

答案 1 :(得分:0)

有问题的文件只不过是序列化的HashMap。

如果你想看到它,首先序列化一个HashMap并找到它。

要序列化,您可以使用以下代码:

HashMap<String,Integer> aHashMap = new HashMap<String,Integer>();  
aHashMap.put("one",1);   
aHashMap.put("two",2);
aHashMap.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用于您提供的程序。

答案 2 :(得分: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应该实现可序列化的接口

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; 
} 
}

执行此操作并查看文件

答案 3 :(得分:-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();
}

(这不包括异常处理和内容,但你明白了......)