知道偏移和长度如何从文件中获取特定字节? [英] How do I fetch specific bytes from a file knowing the offset and length?

查看:139
本文介绍了知道偏移和长度如何从文件中获取特定字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,文件的前4个字节是神奇的,例如 LOL
我怎样才能获得这些数据?

I have a file, and the first 4 bytes of the file are the magic such as LOL . How would I be able to get this data?

我想象它会是这样的:

byte[] magic = new byte[4];
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.read(magic, 0, magic.length);
System.out.println(new String(magic));

输出:

LOL

可悲的是,这对我不起作用。我找不到获取特定值的方法。

Sadly this isn't working for me. I can't find a way to fetch specific values.

有没有人看到任何方法来解决这个问题?

Does anyone see any way to solve this issue?

推荐答案

使用 RandomAccessFile.seek() 定位到您想要读取的位置和 RandomAccessFile.readFully() 读取一个完整的字节数组。

byte[] magic = new byte[4];
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0L);
raf.readFully(magic);
System.out.println(new String(magic));

代码的问题在于,当您以读写模式创建文件时,很可能是文件指针指向文件的末尾。使用 seek()方法进行定位。

The problem with your code is that when you create the file in read-write mode, most likely the file pointer points to the end of the file. Use the seek() method to position.

此外,你可以使用 RandomAccessFile.read( byte [] b,int off,int len) 方法,但偏移和长度对应于数组中的偏移 从哪里开始存储读取bytes和length指定从文件中读取的字节数。但数据仍会从文件的当前位置中读取,而不是从关闭位置读取。

Also you can use the RandomAccessFile.read(byte[] b, int off, int len) method too, but the offset and length corresponds to the offset in the array where to start storing the read bytes, and length specifies how many bytes to read from the file. But the data will still be read from the current position of the file, not from the off position.

所以一旦你打电话给 seek(0L); ,这个读取方法也有效:

So once you called seek(0L);, this read method also works:

raf.read(magic, 0, magic.length);

另请注意,读写方法会自动移动当前位置,例如寻求 0L ,然后读取4个字节(你的魔术字)将导致当前指针移动到 4L 。这意味着您可以随后调用读取方法而无需在每次读取之前进行搜索,并且它们将按位置读取文件的连续部分,它们将不会从相同位置读取。

Also note that the read and write methods will automatically move the current position, so for example seeking to 0L, then reading 4 bytes (your magic word) will result in the current pointer being moved to 4L. This means you can call read methods subsequently without having to seek before each read and they will read a continuous portion of the file increasing by position, they will not read from the same position.

最后注意:

从<$ c创建字符串时$ c> byte 数组,引自 String(byte [] bytes)

When creating a String from a byte array, quoting from the javadoc of String(byte[] bytes):

使用平台的默认字符集解码指定的字节数组构造一个新的字符串。

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

因此将使用平台的默认字符集,这些字符集可能在不同平台上有所不同。总是指定一个正确的编码,如下所示:

So the platform's default charset will be used which may be different on different platforms. Always specify a correct encoding like this:

new String(magic, StandardCharsets.UTF_8);

这篇关于知道偏移和长度如何从文件中获取特定字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆