java对象序列化字符串_java – 如何将一个对象序列化成一个字符串

Sergio:

你应该使用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

AABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值