Java 将十六进制中的字节转换为实际字节

Java 将十六进制中的字节转换为实际字节,java,Java,我有一个像这样用字节写的文件 \r\x00\x00\x00\xd0{"a": "test"} 其中包含以下字节 [13, 0, 0, 0, -48, 123, 34, 97, 34, 58, 32, 34, 116, 101, 115, 116, 34, 125] 当这个文件被读入Java时,我将所有内容都转义了 \\r\\x00\\x00\\x00\\xd0{"a": "test"} 当我对这个字符串执行.getBytes()时,我得到 [92, 114, 92, 120, 48, 48

我有一个像这样用字节写的文件

\r\x00\x00\x00\xd0{"a": "test"}
其中包含以下字节

[13, 0, 0, 0, -48, 123, 34, 97, 34, 58, 32, 34, 116, 101, 115, 116, 34, 125]
当这个文件被读入Java时,我将所有内容都转义了

\\r\\x00\\x00\\x00\\xd0{"a": "test"}
当我对这个字符串执行
.getBytes()
时,我得到

[92, 114, 92, 120, 48, 48, 92, 120, 48, 48, 92, 120, 48, 48, 92, 120, 100, 48, 123, 34, 97, 34, 58, 32, 34, 116, 101, 115, 116, 34, 125]
我必须将字符串转换为有效字节,不幸的是,我无法更改文件的读取方式。我知道在Python中,您可以使用
'rb'
模式打开一个文件,然后就可以开始了。如果java有这种能力,我就不能使用它

简而言之,如何将Java读取的字符串转换为写入文件的原始字节数组

很抱歉,如果这个问题很简单,但我对Java太生疏了

编辑:所以我相信我的问题与提议的“重复问题”链接不同。它不是将java字符串中的每个文本值都转换回一个字节。java中的字符串已被读取器转义
\x00
现在是
\\x00
,它不是相同的字节值。所以我想我需要一些方法来解开绳子

在十六进制编辑器中查看的文件

0000000: 5c72 5c78 3030 5c78 3030 5c78 3030 5c78  \r\x00\x00\x00\x
0000010: 6430 7b22 6122 3a20 2274 6573 7422 7d0a  d0{"a": "test"}.
0000000: 5c5c 725c 5c78 3030 5c5c 7830 305c 5c78  \\r\\x00\\x00\\x
0000010: 3030 5c5c 7864 307b 2261 223a 2022 7465  00\\xd0{"a": "te
0000020: 7374 227d 0a                             st"}.
java在十六进制编辑器中查看的字符串

0000000: 5c72 5c78 3030 5c78 3030 5c78 3030 5c78  \r\x00\x00\x00\x
0000010: 6430 7b22 6122 3a20 2274 6573 7422 7d0a  d0{"a": "test"}.
0000000: 5c5c 725c 5c78 3030 5c5c 7830 305c 5c78  \\r\\x00\\x00\\x
0000010: 3030 5c5c 7864 307b 2261 223a 2022 7465  00\\xd0{"a": "te
0000020: 7374 227d 0a                             st"}.
当用Java读取文件时,不会得到“所有转义”。你为什么这么想?对字节的转换表明,
字符串
正好包含十六进制编辑器在文件中显示的内容。换句话说,

92、114、92、120、48、48、92、120、48、48、92、120、48、48、48、92、120(十进制)

5c72 5c78 3030 5c78 3030 5c78 3030 5c78(六角)


如果你想解码文件中的转义序列,你需要写一些代码来处理它们;这不是字符编码问题。

在Java中,您必须解释输入字符串以获得所需的字节值

我编写了一个解释输入字符串的Java应用程序

以下是输入字符串:

\r\x00\x00\x00\xd0{"a": "test"}
结果如下:

[13, 0, 0, 0, -48, 34, 97, 34, 58, 32, 34, 116, 101, 115, 116, 34, 125]
这是代码。您可能需要对代码进行一些修改,以处理您没有提出问题的情况

package com.ggl.testing;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConvertBytes implements Runnable {

    private String fileName;

    public static void main(String[] args) {
        new ConvertBytes("bytes.txt").run();
    }

    public ConvertBytes(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void run() {
        BufferedReader br = null;

        try {
            br = new BufferedReader(new InputStreamReader(getClass()
                    .getResourceAsStream(fileName)));
            String line = "";
            while ((line = br.readLine()) != null) {
                processLine(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void processLine(String line) {
        String[] parts = line.split("(?=\\\\)");
        List<Byte> byteList = new ArrayList<Byte>();

        for (int i = 0; i < parts.length; i++) {
            if (parts[i].equals("")) {
                continue;
            } else {
                byteList.addAll(getValue(parts[i]));
            }
        }

        Byte[] bytes = byteList.toArray(new Byte[byteList.size()]);
        System.out.println(Arrays.toString(bytes));
    }

    private List<Byte> getValue(String s) {
        List<Byte> byteList = new ArrayList<Byte>();

        if (s.startsWith("\\x")) {
            int value = Integer.valueOf(s.substring(2, 4), 16);
            if (value > 127) {
                value = value - 256;
            }
            byteList.add(Byte.valueOf((byte) value));
            if (s.length() > 4) {
                byteList.addAll(getAsciiValue(s.substring(4)));
            }
        } else if (s.equals("\\r")) {
            byteList.add(Byte.valueOf((byte) 13));
        } else if (s.equals("\\t")) {
            byteList.add(Byte.valueOf((byte) 9));
        } else {
            byteList.addAll(getAsciiValue(s));
        }

        return byteList;
    }

    private List<Byte> getAsciiValue(String s) {
        List<Byte> byteList = new ArrayList<Byte>();

        for (int i = 0; i < s.length(); i++) {
            int value = (int) s.charAt(i);
            byteList.add(Byte.valueOf((byte) value));
        }

        return byteList;
    }

}
package com.ggl.testing;
导入java.io.BufferedReader;
导入java.io.FileNotFoundException;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入java.util.array;
导入java.util.List;
公共类ConvertBytes实现可运行{
私有字符串文件名;
公共静态void main(字符串[]args){
新的ConvertBytes(“bytes.txt”).run();
}
公共字节(字符串文件名){
this.fileName=文件名;
}
@凌驾
公开募捐{
BufferedReader br=null;
试一试{
br=新的BufferedReader(新的InputStreamReader(getClass())
.getResourceAsStream(文件名));
字符串行=”;
而((line=br.readLine())!=null){
生产线;
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
如果(br!=null){
br.close();
}
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
私有void进程行(字符串行){
String[]parts=line.split((?=\)”;
List byteList=new ArrayList();
对于(int i=0;i127){
值=值-256;
}
添加(Byte.valueOf((Byte)value));
如果(s.长度()>4){
addAll(getascivalue(s.substring(4));
}
}如果(s等于(\\r)),则为else{
byteList.add(Byte.valueOf((Byte)13));
}如果(s等于(\\t)),则为else{
byteList.add(Byte.valueOf((Byte)9));
}否则{
byteList.addAll(getascivalue(s));
}
返回byteList;
}
私有列表GetAscivalue(字符串s){
List byteList=new ArrayList();
对于(int i=0;i

bytes.txt文件必须与Java应用程序位于同一目录中。

看起来您必须自己解析“字符串”行

我将有一个转义字符的映射('\r'、'\n'、'\b'等…)

私有静态映射转义字符;
静止的{
escapedCharacters=新HashMap();
转义字符。put(“\\b”,(字节)“\b”);
转义字符。放入(“\\f”,(字节)“\f”);
转义字符。put(“\\n”,(字节)“\n”);
转义字符。put(“\\r”,(字节)“\r”);
转义字符。put(“\\t”,(字节)'\t');
//如果需要,添加更多
};
然后执行以下操作以处理您的文件:

public static void main(String[] args) throws Exception {
    String myFile = "PathToYourFile";

    // Read your file in
    List<String> myFileLines = Files.readAllLines(Paths.get(myFile));

    // List to hold all the lines as translated bytes
    List<byte[]> myFileLinesAsBytes = new ArrayList<>();
    for (String line : myFileLines) {
        myFileLinesAsBytes.add(translateEscapedBytes(line));
    }

    // Displays all translated lines
    for (byte[] byteLine : myFileLinesAsBytes) {
        System.out.println(Arrays.toString(byteLine));
    }
    System.out.println();
}

private static byte[] translateEscapedBytes(String line) throws UnsupportedEncodingException {
    List<Byte> translatedBytes = new ArrayList<>();
    for (int i = 0; i < line.length();) {
        if (line.charAt(i) == '\\') { // Escaped byte
            String escapedByte = line.substring(i, i + 2);
            if (escapedByte.endsWith("x")) { // Hexidecimal number
                escapedByte = line.substring(i + 2, i + 4); // + 4 to get the two numbers after \x
                translatedBytes.add(hexStringToByte(escapedByte));
                i += 4;
            } else { // Escaped character
                translatedBytes.add(escapedCharacters.get(escapedByte));
                i += 2;
            }
        } else { // Non Escapted Character
            translatedBytes.add((byte)(line.charAt(i)));
            i++;
        }
    }

    // Copy List to actual byte[] to return
    byte[] result = new byte[translatedBytes.size()];
    for (int i = 0; i < translatedBytes.size(); i++) {
        result[i] = translatedBytes.get(i);
    }
    return result;
}

private static byte hexStringToByte(String s) {
    return (byte) ((Character.digit(s.charAt(0), 16) << 4) + Character.digit(s.charAt(1), 16));
}
publicstaticvoidmain(字符串[]args)引发异常{
字符串myFile=“pathtoyurfile”;
//在中读取您的文件
列出myFileLines=Files.readAllLines(path.get(myFile));
//列表以将所有行保存为已翻译的字节
List myFileLinesAsBytes=new ArrayList();
for(字符串行:myFileLines){
添加(translateEscapedBytes(行));
}
//显示所有已翻译的行
对于(字节[]byteLine:myFileLinesAsBytes){
System.out.println(Arrays.toString(byteLine));
}
System.out.println();
}
专用静态字节[]tr