2015-11-12 47 views
-2

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

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); 
} 
+0

您正在寻找系列化,我认为,谷歌它! –

+2

你不能使用'ObjectOutputStream';你也必须知道你的字符串使用什么编码。使用'DataOutputStream'。 – fge

+2

另外,你知道你的C代码是依赖于代码的,对吧? – fge

回答

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; 
}