读取文件的前4个字节

3

我习惯使用C#,但是我正在尝试创建一个应用程序,将前四个字节读入数组中,但我一直没有成功。

我还需要在Java中对该文件进行Endian反转,不知道如何操作,在C#中可以使用Array.Reverse(bytes);。我已经尝试将文件读取为Int32,但由于某些原因,我无法将其放入数组中。


12
请给我们展示你尝试过的来源。 - Andremoniy
我会编辑一下我尝试过的内容。 - Z61
2个回答

19

就像这样:

byte[] buffer = new byte[4];
InputStream is = new FileInputStream("somwhere.in.the.dark");
if (is.read(buffer) != buffer.length) { 
    // do something 
}
is.close();
// at this point, the buffer contains the 4 bytes...

2

您可以使用ByteBuffer更改Endianness(字节序)。

FileChannel fc = new FileInputStream(filename).getChannel();
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteBuffer.nativeOrder()); // or whatever you want.
fc.read(bb);
bb.flip();
int n = bb.getInt();

简单的方法来反转一个整数的字节。
int n = ...
int r = Integer.reverseByte(n);

同样地
long l = Long.reverseBytes(n);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接