有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从文本文件中读取存储的哈希表?

我有一个Hashtable<String, String>table包含要存储在文本文件中的数据,我将其存储为Object,如下所示:

Hashtable<String, String>table1=new Hashtable<String,String>();
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(table1);
oos.close();
fos.close();

然后我试着像Object一样阅读它,因为我是这样存储的:

Hashtable<String, String>table2=new Hashtable<String,String>();
FileInputStream reader=new FileInputStream(file);;
ObjectInputStream buffer=new ObjectInputStream(reader);
Object obj=buffer.readObject();
table2=(Hashtable<String, String>)obj;
buffer.close();
reader.close();

但问题是table2仍然是空的!!我认为问题在于阅读方式,请问有什么有用的阅读方式吗


共 (1) 个答案

  1. # 1 楼答案

    我建议您使用^{}而不是Hashtable<String, String>并对^{}接口进行编程,我还建议您使用^{},最后确保在序列化之前将某些内容存储在Collection

    File f = new File(System.getProperty("user.home"), "test.ser");
    Map<String, String> table1 = new HashMap<>();
    table1.put("Hello", "world");
    try (FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos = new ObjectOutputStream(fos);) {
        oos.writeObject(table1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    try (FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois = new ObjectInputStream(fis);) {
        Map<String, String> table = (Map<String, String>) ois.readObject();
        System.out.println(table);
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    输出是

    {Hello=world}