2

ヘキサデータを含む文字列があります。生のヘキサファイルとして保存したい。

だから私は次のような文字列を持っています:

String str ="0105000027476175675C6261636B6772";

私がしなければならないことは、バイト単位で同じデータを持つ file.hex を取得することです。

私がそれをしようとしていたとき:

PrintStream out = new PrintStream("c:/file.hex");
out.print(str);

私は持っているファイルを取得します

"0105000027476175675C6261636B6772"

しかし、ヘキサでは次のようになります。

30 31 30 35 30 30 30 30 32 37 34 37 36 31 37 35 36 37 35 43 36 32 36 31 36 33 36 42 36 37 37 32

私の目標は、ヘキサで持つファイルを持つことです

01 05 00 00 27 47 61 75 67 5C 62 61 63 6B 67 72

4

3 に答える 3

4

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 つずつ書き込むか、配列を作成して格納することができます。

byteorbyte[]を出力ストリームに書き込むには:

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();
    }
}
于 2013-07-31T13:21:31.340 に答える
0

文字列を短い配列に変換して保存する必要があります。

于 2013-07-31T13:18:40.157 に答える