在Python中创建Java DataInputStream数据
我有一个Java程序,它使用在Python中创建Java DataInputStream数据,java,python,Java,Python,我有一个Java程序,它使用DataInputStream存储对象数据 例如: DataInputStream tInput = new DataInputStream(getClass().getResourceAsStream(aDirectory + "/ResultItemInfo.dat")); this._text = tInput.readUTF(); this._image = tInput.readUTF(); this._audio = tInput.r
DataInputStream
存储对象数据
例如:
DataInputStream tInput = new DataInputStream(getClass().getResourceAsStream(aDirectory + "/ResultItemInfo.dat"));
this._text = tInput.readUTF();
this._image = tInput.readUTF();
this._audio = tInput.readUTF();
this._random = false;
if (tInput.read() == 1) {
this._random = true;
}
this._hasMenu = false;
if (tInput.read() == 1) {
this._hasMenu = true;
}
很好,不是吗
有一个现有的数据集,现在我必须添加一些记录。如果我需要制作的工具也是用Java编写的,这将非常简单。不幸的是,它是用Python编写的,因此我必须找到一种方法来创建可以使用Python从Java应用程序读取的文件
有什么简单的方法可以做到这一点吗
作为最后手段,我可以:
- 修改Java应用程序并使用XML。这将破坏与所有现有数据的兼容性,所以我真的不想这样做
- 使用Jython。可能的解决方案,但我想要纯C-Python
- 对数据格式进行反向工程。这也不是一个好办法
readUTF()
可以读取的方式编写unicode字符串data
:
encoded = data.encode('UTF-8')
count = len(encoded)
msb, lsb = divmod(count, 256) # split to two bytes
outfile.write(chr(msb))
outfile.write(chr(lsb))
outfile.write(encoded)
outfile
必须以二进制模式打开(例如“wb
”)。
这是根据Java接口的描述
DataInput
。不过,我并没有尝试运行此操作。要使字符串可读,它必须包含两个字节的计数器,然后正好包含计数器所说的UTF-8编码数据字节数
因此,我建议这段代码应该以readUTF()
可以读取的方式编写unicode字符串data
:
encoded = data.encode('UTF-8')
count = len(encoded)
msb, lsb = divmod(count, 256) # split to two bytes
outfile.write(chr(msb))
outfile.write(chr(lsb))
outfile.write(encoded)
outfile
必须以二进制模式打开(例如“wb
”)。
这是根据Java接口的描述DataInput
。不过,我没有试着运行这个