Sérialisation d'objets dans une String
Bonjour,
J'ai une erreur dans le code suivant :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
public String serialize(Object obj){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(baos);
} catch (IOException e) {
e.printStackTrace();
}
try {
out.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
return new String(baos.toByteArray());
}
public Object deserialize(String str){
ObjectInputStream in = null;
ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
try {
in = new ObjectInputStream(bais);
} catch (IOException e) {
e.printStackTrace();
} // ligne posant problème
try {
return in.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return null;
}
String str = "test";
String serial = serialize(str);
System.out.println(serial);
String newstr = (String) deserialize (serial);
System.out.println(newstr); |
L'erreur est :
java.io.StreamCorruptedException: invalid stream header: EFBFBDEF
Je n'ai rien trouvé de fiable sur le net pour sérializer un objet dans une string.
Une idée ?
Christian