2 つの 16 進数が 1 バイトになります。
File file = new File("yourFilePath");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
string.substring()
次に、メソッドを使用して一度に 2 つの文字を取得して、文字列をループします。
ここでは良いオプションだと思うかもしれByte.parseByte(theTwoChars, 16)
ませんが、バイトが署名されていると見なされるため、惨めに失敗します。代わりに次を使用する必要があります。
byte b = (byte) ( Integer.parseInt(theTwoChars, 16) & 0xFF )
バイトを 1 つずつ書き込むか、配列を作成して格納することができます。
byte
orbyte[]
を出力ストリームに書き込むには:
bos.write(bytes);
最後に、ストリームを閉じます。
bos.close();
これを実証するために私が作成した完全に機能する方法を次に示します。
public static void bytesToFile(String str, File file) throws IOException {
BufferedOutputStream bos = null;
try {
// check for invalid string
if(str.length() % 2 != 0) {
throw new IllegalArgumentException("Hexa string length is not even.");
}
if(!str.matches("[0-9a-fA-F]+")) {
throw new IllegalArgumentException("Hexa string contains invalid characters.");
}
// prepare output stream
bos = new BufferedOutputStream(new FileOutputStream(file));
// go through the string and make a byte array
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < bytes.length; i++) {
String twoChars = str.substring(2 * i, 2 * i + 2);
int asInt = Integer.parseInt(twoChars, 16);
bytes[i] = (byte) (asInt & 0xFF);
}
// write bytes
bos.write(bytes);
} finally {
if (bos != null) bos.close();
}
}