如何在java中将对象写入文件?

时间:2015-11-12 13:39:23

标签: java c

我想将以下c代码转换为java。我以某种方式做到了这一点但是,在写完文件之后,我比较了两种不同的内容,并且有很多不同。 请建议我如何在java中编写与c

相同的内容

C代码:

const struct bin_header bin_header = {
 .magic = "VVN",
 .header_size = 0x10,
 .version = (0x01 << 24) | 0x010000,
 .core = (0x02 << 24) | 0x000501,
};
FILE* ofp = fopen(outfilename, "wb");
fwrite(&bin_header, sizeof(bin_header), 1, ofp)

Java代码:

/* class because there is no struct in java */ 
class bin_header implements Serializable      {
    String magic;
    long header_size;
    long version;
    long core;

    bin_header () { 
        magic = "VVN";
        header_size = 0x10;
        version = (0x01 << 24) | 0x010000;
        core = (0x02 << 24) | 0x000501;
      }

  };

/ *写入* /

的功能
writeByVVN() {
    bin_header bin_header = new bin_header();
    Fout = new FileOutputStream(outFile);
    ObjectOutputStream oos = new ObjectOutputStream(Fout);
    oos.writeObject(bin_header);
}

1 个答案:

答案 0 :(得分:0)

我找到了一种将对象成员写入具有字节序的文件的方法。  我使用了ByteBuffer

   int write(FileOutputStream fout) throws IOException {
            int bytes;
            FileChannel fChan = fout.getChannel();
        ByteBuffer str = ByteBuffer.wrap(magic.getBytes());
        bytes = fChan.write(str);

        ByteBuffer buf = ByteBuffer.allocate(4);
        buf.order(ByteOrder.LITTLE_ENDIAN);

        buf.putInt(header_size);
        buf.rewind();
        bytes  += fChan.write(buf);
        buf.clear();
        ...

        return bytes;
   }

int read(FileInputStream fIn)  throws IOException {
    int bytes = 0;
    FileChannel fChan = fIn.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.order(ByteOrder.LITTLE_ENDIAN);

    bytes = fChan.read(buf);
    buf.rewind();
    magic = new String(buf.array());
    buf.clear();

    ...

    return bytes;
}