2011-01-20 65 views
1

在Java的字節序列,是有圖書館的任何地方,將給出一個字節序列(最好表現爲十六進制),轉化爲給定的InputStream另一個字節序列?例如:翻譯給出的InputStream

InputStream input = new FileInputStream(new File(...)); 
OutputStream output = new FileOutputStream(new File(...)); 
String fromHex = "C3BEAB"; 
String toHex = "EAF6" 
MyMagicLibrary.translate(fromHex, toHex, input, output) 

因此,如果輸入的文件(十六進制看起來像)

00 00 12 18 33 C3 BE AB 00 23 C3 BE AB 00 

轉換後,其結果將是

00 00 12 18 33 EA F6 00 23 EA F6 00 
+2

並不清楚你的要求。什麼是「翻譯成另一個字節序列」呢? 「MyMagicLibrary」上的``translate'方法究竟應該做什麼? – 2011-01-20 15:35:08

+0

所以你想要一個文件並用一些其他的字節序列替換所有出現的字節序列。我不認爲有一個圖書館可以這樣做,但編寫自己的圖書並不難。 – 2011-01-20 15:58:06

回答

2

一旦我做了這樣的事情(爲平凡的補丁EXE文件)使用正則表達式。我將整個輸入讀入byte[]並使用latin1轉換爲String,然後進行替換並轉換回來。它效率不高,但根本無關緊要。你不需要正則表達式,簡單的String.replace就可以。

但在你的情況下,可以很簡單也很高效地完成:

int count = 0; 
while (true) { 
    int n = input.read(); 
    if (n == (fromAsByteArray[count] & 255)) { 
     ++count; 
     if (count==fromAsByteArray.length) { // match found 
      output.write(toAsByteArray); 
      count = 0; 
     } 
    } else { // mismatch 
     output.write(fromAsByteArray, 0, count); // flush matching chars so far 
     count = 0; 
     if (n == -1) break; 
     output.write(n); 
     } 
    } 
} 
0

如果妳意味着ü要使用一類界河從十六進制轉換,以及這裏詛咒 的兩種方法我usualluy使用,美國可以把它們放在一個類內部和重用任何其中u希望

public static String toHex(byte buf[]) { 
    StringBuffer strbuf = new StringBuffer(buf.length * 2); 
    int i; 

    for (i = 0; i < buf.length; i++) { 
     if (((int) buf[i] & 0xff) < 0x10) { 
      strbuf.append("0"); 
     } 

     strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); 
    } 

    return strbuf.toString(); 
} 

public static byte[] fromHexString(String s) { 
    int len = s.length(); 
    byte[] data = new byte[len/2]; 
    for (int i = 0; i < len; i += 2) { 
     data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) 
       + Character.digit(s.charAt(i + 1), 16)); 
    } 
    return data; 
} 

其實我不明白,在每一行代碼,但我通常重用他們。

0

由於您的輸入可以有空格,那麼你首先需要擦洗你的輸入以刪除空格。讀完一對字符後,只需使用Byte.parseByte(twoCharString,16),然後使用String.format轉換回String。

否則它逐字節將最有可能是非常低效的,但是容易測試。一旦你得到了你想要的結果,你可以通過讀取和解析整個緩衝區並一次性吐出多個結果字節來進行調整,每行格式化可能需要16「字節」字符。這一點完全取決於你。

0

實現此目的的一種方法是使用IOUtils和String替換方法。

public static void translate(byte[] fromHex, byte[] toHex, InputStream input, OutputStream output) throws IOException { 
    IOUtils.write(translate(fromHex, toHex, IOUtils.toByteArray(input)), output); 
} 

public static byte[] translate(byte[] fromHex, byte[] toHex, byte[] inBytes) throws UnsupportedEncodingException { 
    String inputText = new String(inBytes, "ISO-8859-1"); 
    String outputText = inputText.replace(new String(fromHex, "ISO-8859-1"), new String(toHex, "ISO-8859-1")); 
    return outputText.getBytes("ISO-8859-1"); 
}