日期:2014-05-20  浏览次数:20690 次

j2me如何从文件中读入一个对象,文件以java对象为单位写入的
以前有些数据只在台式机上使用,是用j2se的ObjectOutputStream写入文件的,但现在想在j2me编程时使用,j2me要用什么方法将它按对象读出,又不破坏数据的结构呢!我是菜鸟,没分送!各位大侠多帮忙啊!谢谢!

------解决方案--------------------
自定义一个序列化/反序列化接口,并对需要写入/读取的对象实现该接口

interface Seriable
{
/* 从流中读取,即反序列化 */
void read(DataInputStream dis);
/* 写入到流中,即序列化 */
void write(DataOutputStream dos);
}

class Example implements Seriable
{
int a;
String b;
/* 实现反序列化 */
public void read(DataInputStream dis)
{
this.a=dis.readInt();
this.b=dis.readUTF();
}
/* 实现序列化 */
public void write(DataOutputStream dos)
{
dos.writeInt(this.a);
dos.writeUTF(this.b);
}
}