在二进制流中搜索字符串(作为byte )

嗨团队,我试图在二进制文件中找到一个字符串“亨利”,并将字符串更改为不同的字符串。 FYI文件是对象序列化的输出。 原始问题在这里

我是新手搜索字节,想象这个代码会搜索我的byte []并交换它。 但它并没有接近工作它甚至找不到匹配。

{ byte[] bytesHenry = new String("Henry").getBytes(); byte[] bytesSwap = new String("Zsswd").getBytes(); byte[] seekHenry = new byte[bytesHenry.length]; RandomAccessFile file = new RandomAccessFile(fileString,"rw"); long filePointer; while (seekHenry != null) { filePointer = file.getFilePointer(); file.readFully(seekHenry); if (bytesHenry == seekHenry) { file.seek(filePointer); file.write(bytesSwap); break; } } } 

好的,我看到bytesHenry==seekHenry问题,并将交换到Arrays.equals( bytesHenry , seekHenry )

我想每次读取5个字节时我需要移动-4个字节的位置。


宾果它现在找到它

  while (seekHenry != null) { filePointer = file.getFilePointer(); file.readFully(seekHenry);; if (Arrays.equals(bytesHenry, seekHenry)) { file.seek(filePointer); file.write(bytesSwap); break; } file.seek(filePointer); file.read(); } 

以下可能适合您,请参阅方法search(byte[] input, byte[] searchedFor) ,它返回第一个匹配匹配的索引,或-1。

 public class SearchBuffer { public static void main(String[] args) throws UnsupportedEncodingException { String charset= "US-ASCII"; byte[] searchedFor = "ciao".getBytes(charset); byte[] input = "aaaciaaaciaojjcia".getBytes(charset); int idx = search(input, searchedFor); System.out.println("index: "+idx); //should be 8 } public static int search(byte[] input, byte[] searchedFor) { //convert byte[] to Byte[] Byte[] searchedForB = new Byte[searchedFor.length]; for(int x = 0; x q = new ArrayDeque(input.length); for(int i=0; i 

从最快的方式使用java在文本文件中查找字符串 :

我在MIMEParser中找到的最佳实现: https : //github.com/samskivert/ikvm-openjdk/blob/master/build/linux-amd64/impsrc/com/sun/xml/internal/org/jvnet/mimepull/ MIMEParser.java

 /** * Finds the boundary in the given buffer using Boyer-Moore algo. * Copied from java.util.regex.Pattern.java * * @param mybuf boundary to be searched in this mybuf * @param off start index in mybuf * @param len number of bytes in mybuf * * @return -1 if there is no match or index where the match starts */ private int match(byte[] mybuf, int off, int len) { 

还需要:

  private void compileBoundaryPattern();