java - 将二进制文件从字符串写入文件

标签 java string algorithm binary

我的代码中有一个字符串,其中包含一堆 0 和 1。现在我想从这个字符串中创建一个文件,里面的位是这个字符串的字符。我该怎么做?

最佳答案

此函数会将二进制字符串解码为字节数组:

static byte[] decodeBinary(String s) {
    if (s.length() % 8 != 0) throw new IllegalArgumentException(
        "Binary data length must be multiple of 8");
    byte[] data = new byte[s.length() / 8];
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '1') {
            data[i >> 3] |= 0x80 >> (i & 0x7);
        } else if (c != '0') {
            throw new IllegalArgumentException("Invalid char in binary string");
        }
    }
    return data;
}

然后你可以用Files.write将字节数组写入文件(或 OutputStream):

String s = "0100100001100101011011000110110001101111"; // ASCII "Hello"
byte[] data = decodeBinary(s);
java.nio.file.Files.write(new File("file.txt").toPath(), data);

关于java - 将二进制文件从字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27668994/

相关文章:

C++ 将大数与运算符重载相加

performance - 当我选择中位数或模式等枢轴时,快速排序的速度并不快

java 8 可选 map() 抛出带有函数引用但不带有完整 lambda 语法的 NPE

java - 即使给出了正确的引用,在 TextView 上获取空对象引用

c++ - 没有正确读取字符串

python - 解码 os.urandom() 字节对象

Java Axis2 ExceptionInInitializerError Web 服务

java - 使用文件集和路径元素在 build.xml 中设置类路径的区别

c - strlen() 返回一个包含 null 终止符的值

algorithm - 创建基于偏好的调度算法