查找偏移量和eof文件到另一个文件

问题描述

早上好。有一个文件,其中包含几个图像。如何获得两点之间的字节链。例如:

文件的字节数

89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 
44 52 00 00 00 40 00 00 00 40 08 02 00 00 
00 25 0B E6 89 00 00 00 09 70 48 59 73 00 
00 0E C4 00 00 0E 49 45 4E 44 AE 42 60 82

Java代码

byte[] header = new byte[] {(byte) 0x89,(byte) 0x50,(byte) 0x4E,(byte) 0x47,(byte) 0x0D,(byte) 0x0A,(byte) 0x1A};

byte[] endBytes = new byte[] {(byte) 0x49,(byte) 0x45,(byte) 0x44,(byte) 0xAE,(byte) 0x42,(byte) 0x60,(byte) 0x82};

RandomAccessFile file = new RandomAccessFile("MY FILE","r");

从现在开始,我不知道如何进行。

如何获取标头和endBytes之间包含的字节字符串?

解决方法

自Java 7起,类java.nio.file.Files具有[静态]方法readAllBytes()。该方法具有一个参数,该参数是要读取的文件的路径,并返回包含整个文件内容的byte[]数组。因此无需RandomAccessFile

您希望文件中除前七个和后八个之外的所有字节。以下代码演示。

/*
 * import java.nio.file.Files;
 * import java.nio.file.Paths;
 */
try {
    byte[] readBytes = Files.readAllBytes(Paths.get("datafile.dat"));
    byte[] requiredBytes = new byte[readBytes.length - 7 - 8];
    System.arraycopy(readBytes,7,requiredBytes,requiredBytes.length);
}
catch (IOException xIo) {
    xIo.printStackTrace();
}