塞爾吉奧:
您應該使用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