java和python二进制文件不能直接读取的解决方案

本文介绍了解决Java与Python在二进制文件读写不兼容的问题,通过自定义DataOutputStream子类实现数据编码顺序调整,确保了两种语言间的数据正确传输。同时,提供了逆向读取二进制文件的DataInputStream子类示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前一阵在做一个项目时,会用到java和python,上下游的关系(java写,python读),但是发现两者的二进制文件无法直接读取,后来发现是由于编码的原因,比如在写入int时,一个是从左到右开始编码,一个是从右到左,所以无法直接读取,因此可以自定义一个写入方法,继承自DataOutputStream来实现

//具体方法就是通过移位来更改写入顺序,使得python能够读取
public class inv_DataOutputStream extends DataOutputStream {
    public inv_DataOutputStream(DataOutputStream out) throws IOException
    { super(out); }
	//写入int的方法
    public final void inv_writeInt(int v) throws IOException {
        out.write((v >>> 0) & 0xFF);
        out.write((v >>> 8) & 0xFF);
        out.write((v >>>16) & 0xFF);
        out.write((v >>>24) & 0xFF);
    }
	//写入long的方法
    private byte writeBuffer[] = new byte[8];
    public final void inv_writeLong(long v) throws IOException {
        writeBuffer[0] = (byte)(v >>> 0);
        writeBuffer[1] = (byte)(v >>> 8);
        writeBuffer[2] = (byte)(v >>> 16);
        writeBuffer[3] = (byte)(v >>> 24);
        writeBuffer[4] = (byte)(v >>> 32);
        writeBuffer[5] = (byte)(v >>> 40);
        writeBuffer[6] = (byte)(v >>> 48);
        writeBuffer[7] = (byte)(v >>> 56);
        out.write(writeBuffer, 0, 8);
    }
}

写好之后就可以直接调用了,强调一点如果写入float,使用的是

wr.inv_writeInt(Float.floatToIntBits(_float));

当时也研究了java读取python二进制的方法,虽然没用到,这里也分享给大家,原理类似,就不写注释了

public class inv_read_binary extends DataInputStream {
    public inv_read_binary(DataInputStream in) throws IOException
    { super(in); }

    public final int read_int() throws IOException {
        int ch1 = in.read();
        int ch2 = in.read();
        int ch3 = in.read();
        int ch4 = in.read();
        if ((ch1 | ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 0) + (ch2 << 8) + (ch3 << 16) + (ch4 << 24));
    }

    public final float read_float() throws IOException {
        return Float.intBitsToFloat(read_int());
    }

    private byte readBuffer[] = new byte[8];
    public final long read_long() throws IOException{
        readFully(readBuffer, 0, 8);
        return (((long)readBuffer[7] << 56) +
                ((long)(readBuffer[6] & 255) << 48) +
                ((long)(readBuffer[5] & 255) << 40) +
                ((long)(readBuffer[4] & 255) << 32) +
                ((long)(readBuffer[3] & 255) << 24) +
                ((readBuffer[2] & 255) << 16) +
                ((readBuffer[1] & 255) << 8) +
                ((readBuffer[0] & 255) << 0));
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值