将大字节字符串写入文件的最有效方法

时间:2013-04-10 22:22:21

标签: java string file byte bytearray

我正在为这样的文件写一串位:

//String to ByteArray
byte[] b = new BigInteger(encodedFile.toString(), 2).toByteArray();
//Writing
FileOutputStream fos = new FileOutputStream(fileName.concat(".file"),true);
fos.write(b);

它可以很好地处理来自100kb但比那个更大的文件的位串,它变得非常慢。

什么是使用更大的位串来实现它的最有效方法?

1 个答案:

答案 0 :(得分:0)

通常,解释位置编号系统中的字符串是非常昂贵的。 BigInteger构造函数未针对基数为2的幂的特殊情况进行优化。通过一些测试就可以看出这一点:

public static void main(String [] args) {
    char[] digits = new char[200000];
    Arrays.fill(digits, '1');
    String s = new String(digits);

    StopWatch watch = new StopWatch("new BigInteger");
    BigInteger bigInt = new BigInteger(s, 2);
    watch.done();
    watch = new StopWatch("toByteArray");
    byte[] data = bigInt.toByteArray();
    watch.done();
}

对于200k数字,打印:

new BigInteger took 0.772188085
toByteArray took 0.001747708

对于100k数字,打印:

new BigInteger took 0.200759594
toByteArray took 0.000973587

显然,新的BigInteger采用O(n ^ 2)算法。

知道我们转换二进制数,我们可以简化转换:

static byte[] convert(String binaryString) {
    // assumes binaryString.length() is a multiple of 8
    byte[] bytes = new byte[binaryString.length() / 8];
    byte data = 0;
    for (int i = 0; i < bytes.length; i++) {
        int minIndex = i * 8;
        int maxIndex = (i + 1) * 8;
        for (int j = minIndex; j < maxIndex; j++) {
            data <<= 1;
            data |= binaryString.charAt(j) - '0';
        }
        bytes[i] = data;
    }
    return bytes;
}

在包含100万个字符的char数组上运行它,我们得到:

new BigInteger took 19.086559046
toByteArray took 0.003656331
convert took 0.009119036

以上代码未经测试,使用风险自负: - )

对于非常大的数字,在转换时将字节写入OutputStream可能是值得的。如果这样做,则应使用BufferedOutputStream。

相关问题