用Java读取结构化二进制文件的最佳方式 [英] Best way to read structured binary files with Java
问题描述
简而言之,文件具有由几个整数,字节和固定长度的char数组组成的标题,后面是一个也由整数和字符组成的记录列表。
在任何其他语言中,我将创建 struct
s(C / C ++)或
s(Pascal / Delphi),它们是头和记录的逐字节表示。然后我会将 sizeof(header)
个字节读入标头变量,并对记录执行相同操作。
这样的东西:(Delphi)
type
THeader = record
版本:整数;
类型:字节;
BeginOfData:Integer;
ID:array [0..15] of Char;
结束
...
程序ReadData(S:TStream);
var
标题:THeader;
begin
S.ReadBuffer(Header,SizeOf(THeader));
...
end;
做什么与Java类似的最好方法是什么?我必须自己读取每一个值,还有其他方式做这种块读吗?
据我所知,Java强制您以字节读取文件,而不是阻止读取。如果您正在序列化Java对象,那将是一个不同的故事。
其他示例使用 DataInputStream 类与文件,但您也可以使用快捷方式: RandomAccessFile 类:
RandomAccessFile in = new RandomAccessFile(filename,r);
int version = in.readInt();
byte type = in.readByte();
int beginOfData = in.readInt();
byte [] tempId;
in.read(tempId,0,16);
String id = new String(tempId);
请注意,您可以将responce对象转换为类,如果这样会更容易。 p>
I have to read a binary file in a legacy format with Java.
In a nutshell the file has a header consisting of several integers, bytes and fixed-length char arrays, followed by a list of records which also consist of integers and chars.
In any other language I would create struct
s (C/C++) or record
s (Pascal/Delphi) which are byte-by-byte representations of the header and the record. Then I'd read sizeof(header)
bytes into a header variable and do the same for the records.
Something like this: (Delphi)
type
THeader = record
Version: Integer;
Type: Byte;
BeginOfData: Integer;
ID: array[0..15] of Char;
end;
...
procedure ReadData(S: TStream);
var
Header: THeader;
begin
S.ReadBuffer(Header, SizeOf(THeader));
...
end;
What is the best way to do something similar with Java? Do I have to read every single value on its own or is there any other way to do this kind of "block-read"?
To my knowledge, Java forces you to read a file as bytes rather than being able to block read. If you were serializing Java objects, it'd be a different story.
The other examples shown use the DataInputStream class with a File, but you can also use a shortcut: The RandomAccessFile class:
RandomAccessFile in = new RandomAccessFile("filename", "r");
int version = in.readInt();
byte type = in.readByte();
int beginOfData = in.readInt();
byte[] tempId;
in.read(tempId, 0, 16);
String id = new String(tempId);
Note that you could turn the responce objects into a class, if that would make it easier.
这篇关于用Java读取结构化二进制文件的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!