`
songbin0201
  • 浏览: 319532 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java IO 篇之ObjectOutputStream、ObjectInputStream

 
阅读更多
public class TransObjectJava implements TransObject{

    @Override
    public Person decoder(String objstr) {
        ObjectInputStream ois = null;
        try {
            ByteArrayInputStream bai = new ByteArrayInputStream(objstr.getBytes());
            ois = new ObjectInputStream(bai);
            Person obj = (Person)ois.readObject();
            return obj;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }finally{
            try {
                ois.close();
                ois = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public String encoder(Person obj) {
        ObjectOutputStream oos = null;
        try{
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bao);
            oos.writeObject(obj);
            return bao.toString();
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally{
            try {
                oos.close();
                oos = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }
}



对象序列化、反序列化过程将对象以string形式输出,以byte[] 方式反序列化成对象
报异常 java.io.StreamCorruptedException: invalid stream header: EFBFBDEF,原因如下:
The provided test code serializes an object to a ByteArrayOutputStream,
converts the generated byte array into a string using the
ByteArrayOutputStream.toString() method, converts the string back into a byte
array using the String.getBytes() method, and then attempts to deserialize the
object from the byte array using a ByteArrayInputStream.  This procedure will
in most cases fail because of the transformations that take place within
ByteArrayOutputStream.toString() and String.getBytes(): in order to convert the
contained sequence of bytes into a string, ByteArrayOutputStream.toString()
decodes the bytes according to the default charset in effect; similarly, in
order to convert the string back into a sequence of bytes, String.getBytes()
encodes the characters according to the default charset.

Converting bytes into characters and back again according to a given charset is
generally not an identity-preserving operation.  As the javadoc for the
String(byte[], int, int) constructor (which is called by
ByteArrayOutputStream.toString()) states, "the behavior ... when the given
bytes are not valid in the default charset is unspecified".  In the test case
provided, the first two bytes of the serialization stream, 0xac and 0xed (see
java.io.ObjectStreamConstants.STREAM_MAGIC), both get mapped to the character
'?' since they are not valid in the default charset (ISO646-US in the JDK I'm
running).  The two '?' characters are then mapped back to the byte sequence
0x3f 0x3f in the reconstructed data stream, which do not constitute a valid
header. 

The solution, from the perspective of the test case, is to use
ByteArrayOutputStream.toByteArray() instead of toString(), which will yield the
raw byte sequence; this can then be fed directly to the
ByteArrayInputStream(byte[]) constructor.


因为序列化时,加入对象header的字节 final static short STREAM_MAGIC = (short)0xaced; 在默认的字符集中为无效字节,标记为?,反序列化时就无法正常还原对象header数据,因此反序列化失败

解决方法如下:
1、序列化输出字节数组  byteArrayOutputStream.toByteArray();
反序列化用字节数组还原对象
2、序列化输出字符串,使用ISO-8859-1编码 byteArrayOutputStream.toSting("ISO-8859-1");反序列化时使用ISO-8859-1编码还原对象 ByteArrayInputStream bai = new ByteArrayInputStream(objstr.getBytes("ISO-8859-1"));
分享到:
评论

相关推荐

    java io 类 小结 代码

    简洁分类 代码直接使用 InputStream OutputStream Reader Writer FileInputStream FileOutputStream FileReader FileWriter InputStreamReader ...ObjectOutputStream ObjectInputStream Scanner

    java项目超市

    import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java....

    java上的即时通信

    import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; import java.io.EOFException; import java.net.ServerSocket; import java.net.Socket; import java.awt....

    学生管理系统

    import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; public class StuC { ArrayList <Student> al=new ArrayList();//类型ArrayList是集合,在定义ArrayList类型...

    java.io常用方法(基本)

    我自己写的一些关于IO中的见解,可以用来参考。 File的增、删、改、查,FileReader和FileWriter类,BufferedReader和BufferedWriter类,ObjectOutputStream和ObjectInputStream类

    java_rpc_demo

    (1)用java写的RPC调用的demo。...(2)没有用到其他的jar包,java对象和流之间的转换用的是java.io.ObjectInputStream和java.io.ObjectOutputStream。 (3)下载解压,可以直接导入Eclipse运行调试。

    Java之IO流学习总结

    Java IO流学习总结 Java流操作有关的类或接口: Java流类图结构: 流的概念和作用 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据...

    JavaIOObjectStreams:FileInputStream 与 ObjectInputStream 和 ObjectOutputStream 的组合

    JavaIO对象流 FileInputStream 与 ObjectInputStream 和 ObjectOutputStream 的组合 奥利弗·缪尔

    Java高级程序设计实战教程第五章-Java序列化机制.pptx

    其中包括以下接口和类: java.io.Serializable java.io.Externalizable ObjectOutput ObjectInput ObjectOutputStream ObjectInputStream Java高级程序设计实战教程第五章-Java序列化机制全文共15页,当前为第7页。...

    bytestreamdemo.zip

    java IO 字节流练习代码 FileInputStream和FileOutputStream BufferedInputStream 和 BufferedOutputStream DataInputStream 和 DataOutputStream ObjectInputStream和ObjectOutputStream PrintStream ...

    android 面试题

    4.java.io包中的objectinputstream和objectoutputstream类主要用于对对象(Object)的读写。 5.android 中service的实现方法是:startservice和bindservice。 6.activity一般会重载7个方法用来维护其生命周期,除了...

    基于JAVA的聊天系统的设计与实现

    import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.*; import qq.dao.hibernate.IServiceDao; import qq.entity.*; public class ...

    java输入输出流 流式输入与输出

    java.io包中,提供了ObjectInputStream和ObjectOutputStream将数据流功能扩展至可读写对象。在ObjectInputStream中用readObject()方法可以直接读取一个对象,ObjectOutputStream中用writeObject()方法可以直接将对象...

    IO体系.java

    |--ObjectOutputStream/:将java对象的基本数据类型和图形写入到OutputStream。 | |--PipedOutputStream/:可以将管道输出流连接到管道输入流来创建通信管道。 | 用方法connect(PipedInputStream snk) 将此管道...

    JAVA实现SOCKET聊天

    用JAVA语言实现网络聊天import java.io.*; import java.net.*; import java.util.*; public class ChatHandler implements Runnable { protected Socket socket; protected ObjectInputStream dataIn; ...

    JAVA基础课程讲义

    ObjectInputStream和ObjectOutputStream 158 PrintStream 158 Reader 158 Writer 159 FileReader和FileWriter 159 BufferReader和BufferWriter 159 InputStreamReader和OutputStreamWriter 161 JAVA对象的序列化和反...

    AIC的Java课程1-6章

     掌握串行化概念,学会使用FileInputStream,FileOutputStream,ObjectInputStream,ObjectOutputStream等类输入输出对象。  明白通过捕获异常判定输入文件流的结束。  [*]知道使用RandomAccessFile...

    DVD项目功能实现

    import java.io.*; import java.util.ArrayList; import java.util.List; public class BaseDaoImpl<T> { protected List<T> read(File file) { FileInputStream fis = null; ObjectInputStream ois = null; ...

    JDK_API_1_6

    Serializable 类通过实现 java.io.Serializable 接口以启用其序列化功能。 类摘要 BufferedInputStream BufferedInputStream 为另一个输入流添加一些功能,即缓冲输入以及支持 mark 和 reset 方法的能力。 ...

    可群发,冒号加客户号可指定用户发送的java聊天程序

    import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.List; public class ChatServer { public static int id; private ServerSocket server; private List<Connection> ...

Global site tag (gtag.js) - Google Analytics