小编Iti*_*ian的帖子

如何读取文件中写的LinkedHashMap?

我想从以.txt文件编写的LinkedHashMap中读取特定值,但显示为“ java.io.StreamCorruptedException:无效的流头:7B495020”

为了在LinkedHashMap中编写代码,我尝试了该方法。

public void WriteBasicInfo(String name, String pass) throws IOException, ParseException {
    Map<String, String> m;
        try {
            m = new LinkedHashMap<String, String>();
            m.put("Name", name);
            m.put("Password", pass);

            BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_NAME, false));
            bw.write(m.toString());
            bw.flush();
            bw.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)

并且成功写入文件。但是当我试图使用这种方法读取上面的哈希图时

public void readBasicInfo() throws IOException, ParseException, InvocationTargetException, ClassNotFoundException 
{
        ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILE_NAME));
        Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();

        for(Map.Entry<String,String> m :myMap.entrySet()){
                 System.out.println(m.getKey()+" : "+m.getValue());
        //  String val1=m.get("Name"); 
        }     
     ois.close();
    }
Run Code Online (Sandbox Code Playgroud)

它显示“ java.io.StreamCorruptedException:无效的流头:7B495020”,并且没有读取任何数据 …

java serialization readfile deserialization

3
推荐指数
1
解决办法
68
查看次数

标签 统计

deserialization ×1

java ×1

readfile ×1

serialization ×1