由于在做迁移项目的时候修改了一些类的目录,导致远程系统在接收序列化字节码的时候报ClassNotFound异常,所以想到的方案是在新项目中修改序列化数据中的路径名称,以下是google到的一个方法:
public static byte[] changePathInSerializedData( byte[] buffer, String fromPath, String toPath ) throws IOException
{
byte[] search = fromPath.getBytes( "UTF-8" );
byte[] replace = toPath.getBytes( "UTF-8" );
ByteArrayOutputStream f = new ByteArrayOutputStream();
for ( int i = 0; i < buffer.length; i++ )
{
// Search 2 bytes ahead to let us modify the 2 bytes length of the class
// name (see Serialize format http://www.javaworld.com/community/node/2915
// )
boolean found = false;
int searchMaxIndex = i + search.length + 2;
if ( searchMaxIndex <= buffer.length )
{
found = true;
for ( int j = i + 2; j < searchMaxIndex; j++ )
{
if ( search[ j - i - 2 ] != buffer[ j ] )
{
found = false;
break;
}
}
}
if ( found )
{
int high = ( (int) ( buffer[ i ] ) & 0xff );
int low = ( (int) ( buffer[ i + 1 ] ) & 0xff );
int classNameLength = ( high << 8 ) + low;
classNameLength += replace.length - search.length;
// Write new length
f.write( ( classNameLength >> 8 ) & 0xff );
f.write( ( classNameLength ) & 0xff );
// Write replacement path
f.write( replace );
i = searchMaxIndex - 1;
}
else
{
f.write( buffer[ i ] );
}
}
f.flush();
f.close();
return f.toByteArray();
}
用法就是将序列化后的byte[]数据调用这个方法:
//data 为对象
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream( out );
objOut.writeObject( data );
objOut.close();
out.close();
return changePathInSerializedData(out.toByteArray(), NEW_PATH, OLD_PATH);
希望可以帮助到需要的人。