java 读取文件的前 4 个字节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14381880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:04:52  来源:igfitidea点击:

Read First 4 Bytes of File

java

提问by Z61

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. 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);. I've tried reading the file into an Int32, but from there I cannot get it into an array for some reason.

我习惯了 C#,但我正在尝试制作一个应用程序,将前 4 个字节读入一个数组,但我没有成功。我还需要反转文件上的字节序,我不知道在 Java 中如何,在 C# 中它是Array.Reverse(bytes);. 我试过将文件读入 Int32,但由于某种原因,我无法将其放入数组。

回答by poussma

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

回答by Peter Lawrey

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