简体   繁体   English

读取文件的前4个字节

[英]Read First 4 Bytes of File

I'm used to C#, but I'm trying to make an app which reads the first 4 bytes into an array, but I have been unsuccessful. 我已经习惯了C#,但是我正在尝试制作一个将前4个字节读入数组的应用程序,但是我一直没有成功。 I also need to reverse the Endian on the file which I don't know how in Java, in C# it is Array.Reverse(bytes); 我还需要反转在Java中不知道的文件上的Array.Reverse(bytes); ,在C#中是Array.Reverse(bytes); . I've tried reading the file into an Int32, but from there I cannot get it into an array for some reason. 我尝试将文件读入Int32,但是由于某种原因,我无法从那里将其读入数组。

Like that : 像那样 :

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...

You can change the Endianness with ByteBuffer 您可以使用ByteBuffer更改字节序

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();

The simple way to reverse the byte of an Integer 反转整数字节的简单方法

int n = ...
int r = Integer.reverseByte(n);

similarly 类似地

long l = Long.reverseBytes(n);

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

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