有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何用Java将字节数组写入文件

我想把字节数组写入文件。这是网页上的代码http://allmybrain.com/2012/03/16/quick-convert-raw-g711-ulaw-audio-to-a-au-file/

    import struct
    header = [ 0x2e736e64, 24, 0xffffffff, 1, 8000, 1 ]
    o=open('out.au','wb')
    o.write ( struct.pack ( ">IIIIII", *header ) )
    raw = open('in.raw','rb').read()
    o.write(raw)
    o.close()

我转换成了java:

            byte []  header= {   0x2e736e64, 24, 0xffffffff, 1, 8000, 1 };
        FileOutputStream out = new FileOutputStream(file);
        out.write(header);

但这是错误的。你能帮我修一下吗。谢谢


共 (1) 个答案

  1. # 1 楼答案

    在python代码中,你写的是32位整数,而不是8位字节; 使用此代码可以得到相同的结果:

     byte []  header= {   0x2e, 0x73, 0x6e, 0x64,
                          0x0,  0x0,  0x0,  24,
                          -1,  -1,    -1,   -1,
                          0,   0,     0,    1,
                          0,   0,     0x1f, 0x40,
                          0,   0,     0,    1 };
     FileOutputStream out = new FileOutputStream(file);
     out.write(header);