如何一次将8个字符串转换为一个字节写入Java中的文件?

How to convert 8 character string into a single byte at a time to write to file in Java?

我正在尝试使用字节将二进制数字字符串压缩到文件中。下面是我尝试通过获取长度为 8 的子字符串并尝试将这 8 个字符转换为一个字节来转换此字符串。基本上让每个角色都有一点。请让我知道是否有更好的方法解决这个问题?我不允许使用任何特殊的库。

编码

public static void encode(FileOutputStream C) throws IOException{

    String binaryString = "1001010100011000010010101011";
    String temp = new String();

    for(int i=0; i<binaryString.length(); i++){
        temp += binaryString.charAt(i);

        // once I get 8 character substring I write this to file
        if(temp.length() == 8){
            byte value = (byte) Integer.parseInt(temp,2);
            C.write(value);
            temp = "";
        }
        // remaining character substring is written to file
        else if(i == binaryString.length()-1){
            byte value = Byte.parseByte(temp, 2);
            C.write(value);
            temp = "";
        }
    }
    C.close();
}

解码

Path path = Paths.get(args[0]);
byte[] data = Files.readAllBytes(path);

for (byte bytes : data){
    String x = Integer.toString(bytes, 2);
}

这些是我正在编码的子字符串:

10010101
00011000
01001010
1011

不幸的是,当我解码时,我得到以下信息:

-1101011
11000
1001010
1011

我会使用以下内容

public static void encode(FileOutputStream out, String text) throws IOException {
    for (int i = 0; i < text.length() - 7; i += 8) {
        String byteToParse = text.substring(i, Math.min(text.length(), i + 8));
        out.write((byte) Integer.parse(byteToParse, 2));
    }
    // caller created the out so should be the one to close it.
}

打印文件

Path path = Paths.get(args[0]);
byte[] data = Files.readAllBytes(path);

for (byte b : data) {
    System.out.println(Integer.toString(b & 0xFF, 2));
}

检查这是否是您要查找的内容:

Byte bt = (byte)(int)Integer.valueOf("00011000", 2);
System.out.println(bt);
System.out.println(String.format("%8s",Integer.toBinaryString((bt+256)%256)).replace(' ', '0'));