版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
最近工作中涉及到匹配文件流,并替换其中数据块的内容,特此记录便于日后查阅,代码如下:
public static Map<String, Integer> search_pattern(byte[] content, byte[] pattern) {
Integer content_len = content.length;
Map<String, Integer> ret = Maps.newHashMap();
Integer count = 0;
for (int i = 16; i <= content_len; i++) {
if ((content[i - 0x10] == pattern[0x00]) &&
(content[i - 0x0f] == pattern[0x01]) &&
(content[i - 0x0e] == pattern[0x02]) &&
(content[i - 0x0d] == pattern[0x03]) &&
(content[i - 0x0c] == pattern[0x04]) &&
(content[i - 0x0b] == pattern[0x05]) &&
(content[i - 0x0a] == pattern[0x06]) &&
(content[i - 0x09] == pattern[0x07]) &&
(content[i - 0x08] == pattern[0x08]) &&
(content[i - 0x07] == pattern[0x09]) &&
(content[i - 0x06] == pattern[0x0a]) &&
(content[i - 0x05] == pattern[0x0b])
) {
ret.put("pattern_len", (content[i - 0x04] << 24) + (content[i - 0x03] << 16) + (content[i - 0x02] << 8) + (content[i - 0x01]));
if (ret.get("pattern_len") + i - 16 <= content_len) {
ret.put("count", ++count);
ret.put("pattern_offset", i - 16);
i += ret.get("pattern_len") - 1;
}
}
}
return ret;
}
注意,上述数据块的字节大小必须是 16 的倍数,否则需要 &0xFF
文件和byte数组转换,代码如下:
/**
* 将文件转为byte数组
*
* @param filename
* @return byte[]
* @author zxzhang
* @date 2019/10/8
*/
public static byte[] file2ByteArray(String filename) throws IOException {
FileChannel fc = null;
try {
fc = new RandomAccessFile(filename, "r").getChannel();
MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0,
fc.size()).load();
byte[] result = new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
byteBuffer.get(result, 0, byteBuffer.remaining());
}
return result;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 将Byte数组转换成文件
*
* @param bytes
* @param filePath
* @param fileName
* @return void
* @author zxzhang
* @date 2019/10/8
*/
public static void byteArray2File(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists()) {// 判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + BootstrapConst.PATH_SEPARATOR + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}