塞尔吉奥:
您应该使用BLOB。这与JDBC非常相似。
您发布的第二个代码的问题是编码。您应该额外编码字节以确保它们都不会失败。
如果您仍想将其写入字符串中,则可以使用java.util.Base64对字节进行编码。
仍然应该使用CLOB作为数据类型,因为您不知道序列化数据将要运行多长时间。
下面是如何使用它的示例。
import java.util.*;
import java.io.*;
/**
* Usage sample serializing SomeClass instance
*/
public class ToStringSample {
public static void main(String [] args) throws IOException,
ClassNotFoundException {
String string = toString(new SomeClass());
System.out.println(" Encoded serialized version ");
System.out.println(string);
SomeClass some = (SomeClass) fromString(string);
System.out.println("\n\nReconstituted object");
System.out.println(some);
}
/** Read the object from Base64 string. */
private static Object fromString(String s) throws IOException ,
ClassNotFoundException {
byte [] data = Base64.getDecoder().decode(s);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data));
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
private static String toString(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
}
/** Test subject. A very simple class. */
class SomeClass implements Serializable {
private final static long serialVersionUID = 1; // See Nick's comment below
int i = Integer.MAX_VALUE;
String s = "ABCDEFGHIJKLMNOP";
Double d = new Double(-1.0);
public String toString(){
return "SomeClass instance says: Don't worry, "
+ "I'm healthy. Look, my data is i = " + i
+ ", s = " + s + ", d = " + d;
}
}
输出:
C:\samples>javac *.java
C:\samples>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T
AABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w
QCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ
DREVGR0hJSktMTU5PUA==
Reconstituted object
SomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0
注意:对Java 7及更早版本,你可以看到原来的answer here
“ByteArrayOutputStream.toString使用*平台默认的编码转换*。您确定要吗?尤其是作为一个任意字节数组是无效的UTF8。此外,数据库将打乱它。“ – 2008-09-25 17:57:44
您应该认真对待Tom Hawtin的上述评论 – anjanb 2008-09-25 18:12:00