前一阵在做一个项目时,会用到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));
}
}