繁体   English   中英

将字节流反序列化为Java类

[英]DeSerializing a byte stream into an Java Class

我已经嵌套了“ C”语言数据结构,如下所示:

struct xyz {
  char a[256];
  char b[1024];
} XYZ;

struct abc {
  unsigned char dat1[1024];
  int dat2;
} ABC;

struct def {
  int x;
  int y;
  int z;
} DEF;

struct tot {
  XYZ p1;
  ABC p2[45];
  DEF p3[17];
} TOT;

TOT tot;

填充TOT之后,我将其写入C程序中的此类文件中。

fwrite((char *)&tot,1,sizeof(TOT),文件);

现在,我必须使用JAVA程序读回相同的文件,并重新创建与对应的ANDROID JAVA类相同的C数据结构。

因此,我使类看起来像上面的C结构,这些类仅包含数据成员,而没有这样的方法

class XYZ {
  byte a[]=new byte[256];
  byte b[]=new byte[1024];
} XYZ;

class ABC {
  byte dat1[1024];
  int dat2;
};

class DEF {
  int x;
  int y;
  int z;
};

class TOT {
  XYZ p1;
  ABC p2[45];
  DEF p3[17];
};

我知道上面的类中有一些语法错误,但我希望您能理解。

那么,如何才能从文件中读取所有字节并使用它来创建所有这些嵌套的JAVA类对象,如上面所见,以匹配顶部的原始C结构?

我猜它就像在JAVA(Android)中进行反序列化,但序列化程序是使用fwrite的C程序。

很难从文件中逐个读取字节,然后手动填写JAVA类对象,而且考虑到从Windows C到JAVA的数据类型和字节顺序的不同大小,是否存在更快的方法?

不幸的是,二进制数据已经使用C写入了文件并且无法更改,因此我必须编写一个JAVA程序来将其取回并从中获取那些类对象。

非常感谢您的任何想法!

你可以用一个做到这一点很容易DataInputStream提供发件人使用网络字节顺序。

如果不是这样,我只能建议您放弃C语言,然后使用正确定义的应用程序协议重新开始。 就像我在这里一直说的,“不要将structs用作应用程序协议。 使用应用程序协议作为应用程序协议。 例如,您可以查看XDR。

将这些结构加载到内存中最简单的方法是使用ByteBuffer ,因为您可以控制字节序。

以下示例将在构建Java对象之前首先将整个文件加载到内存中。 由于Java对象将占用更多的内存,因此这不是主要问题。

类的字段也已更正。

该代码假定为低端字节序(x86处理器),并且C int为4字节,即映射到Java int

ByteBuffer buffer = ByteBuffer.wrap(Files.readAllBytes(Paths.get("C:/fileFromC.bin")));
buffer.order(ByteOrder.LITTLE_ENDIAN); // if C code was run on x86 processor
TOT tot = TOT.load(buffer);
class XYZ {
    byte a[] = new byte[256];
    byte b[] = new byte[1024];
    static XYZ load(ByteBuffer buffer) {
        XYZ xyz = new XYZ();
        buffer.get(xyz.a);
        buffer.get(xyz.b);
        return xyz;
    }
}
class ABC {
    byte[] dat1 = new byte[1024];
    int dat2;
    static ABC load(ByteBuffer buffer) {
        ABC abc = new ABC();
        buffer.get(abc.dat1);
        abc.dat2 = buffer.getInt();
        return abc;
    }
}
class DEF {
    int x;
    int y;
    int z;
    static DEF load(ByteBuffer buffer) {
        DEF def = new DEF();
        def.x = buffer.getInt();
        def.y = buffer.getInt();
        def.z = buffer.getInt();
        return def;
    }
}
class TOT {
    XYZ p1;
    ABC[] p2 = new ABC[45];
    DEF[] p3 = new DEF[17];
    static TOT load(ByteBuffer buffer) {
        TOT tot = new TOT();
        tot.p1 = XYZ.load(buffer);
        for (int i = 0; i < tot.p2.length; i++)
            tot.p2[i] = ABC.load(buffer);
        for (int i = 0; i < tot.p3.length; i++)
            tot.p3[i] = DEF.load(buffer);
        return tot;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM