【发布时间】:2014-10-20 12:56:50
【问题描述】:
这是我的代码:
try {
Uri uri = Uri.parse("file:///storage/emulated/0/Download/information.csv");
File file = new File(uri.getPath());
//Read the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
boolean firstLine = true;
while ((line = br.readLine()) != null) {
System.out.println("Print the contents from the file :" + line);
if (firstLine) {
firstLine = false;
continue;
} else {
//deserialize the string to Object
td = TransferData.fromString(line); //Where td is an object
//deserialize the string to Object
System.out.println("deserialized: " + td);
}
但是,我在这一行遇到了一个异常:
td = TransferData.fromString(line);
从我的 fromString 函数:
/** Read the object from Base64 string. */
public static TransferData fromString( String s ) throws IOException, ClassNotFoundException {
byte [] data = Base64.decode(s, Base64.DEFAULT);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return (TransferData)o;
}
例外是 StreamCorruptedException 但我不确定为什么会这样。我希望能够读取字符串并反序列化字符串。
编辑:
/** Write the object to a Base64 string. */
public static String toString(Serializable o) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(output);
oos.writeObject(o);
oos.close();
return new String(Base64.encode(output.toByteArray(), Base64.DEFAULT));
}
//SerialVersionID
private static final int serialVersionUID = 10032014;
【问题讨论】:
-
你的
ObjectOutputStream在哪里?您要反序列化哪个对象?您确定serialVersionUID配置正确吗? -
请记住,根据 Javadoc,
ObjectInputStream会反序列化以前使用ObjectOutputStream编写的原始数据和对象。 如果您的目标是从文件ObjectInputStream是not what you need。 -
嗯,事情就是这样。我有两个设备,一个设备接收一个对象并将其转换为字符串。然后将字符串保存到文件中。其他设备读取该文件中的字符串并对其进行反序列化。
-
我的 objectOutputStream 在我的 toString 方法中。我在哪里需要输出流?
-
StreamCorruptedException 是“当从对象流中读取的控制信息违反内部一致性检查时抛出。”这意味着您将对象序列化为文件的代码不正确。
标签: java android serialization