Iti*_*ian 3 java serialization readfile deserialization
我想从以.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”,并且没有读取任何数据
我试图读取所有用hashmap编写的条目,以检查是否正在读取;但实际上我只想读取存储在哈希图中的“名称”条目。
您很简单:编写为字符串,但是读回一个二进制序列化对象!
您知道,这就像:您将鸡蛋放入一个盒子中,然后期望您可以打开该盒子并将牛奶倒入杯子中!那行不通。
这里:
bw.write(m.toString());
Run Code Online (Sandbox Code Playgroud)
您将映射作为原始字符串写入该文件。这意味着您的文件现在包含人类可读的字符串!
但是然后您这样做:
Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();
Run Code Online (Sandbox Code Playgroud)
希望该文件包含序列化的对象。
长话短说,这些是您的选择:
我的建议:选择选项2或3。2将依赖关系添加到第三方库中,但我认为这是如今更为“常见”的做法。