如何读取使用python的struct.pack方法编写的java中的String [英] How to read String in java that was written using python's struct.pack method

查看:549
本文介绍了如何读取使用python的struct.pack方法编写的java中的String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用struct.pack
将信息写入python中的文件。

I have written information to a file in python using struct.pack eg.

out.write( struct.pack(">f", 1.1) );
out.write( struct.pack(">i", 12) );
out.write( struct.pack(">3s", "abc") );

然后我在java中使用 DataInputStream 阅读它和 readInt readFloat readUTF
读取数字有效,但一旦我打电话给 readUTF()我得到 EOFException

Then I read it in java using DataInputStream and readInt, readFloat and readUTF. Reading the numbers works but as soon as I call readUTF() I get EOFException.

我认为这是因为正在编写的字符串的格式和java读取它的方式不同,或者我做错了什么?

I assume this is because of the differences in the format of the string being written and the way java reads it, or am I doing something wrong?

如果它们不兼容,是否有另一种读写字符串的方法?

If they are incompatible, is there another way to read and write strings?

推荐答案

预期的格式通过 readUTF()记录这里。简而言之,它期望一个16位的大端长度后跟字符串的字节。所以,我认为你可以修改你的打包电话看起来像这样:

The format expected by readUTF(), is documented here. In short, it expects a 16-bit, big-endian length followed by the bytes of the string. So, I think you could modify your pack call to look something like this:

s = "abc"
out.write( struct.pack(">H", len(s) ))
out.write( struct.pack(">%ds" % len(s), s ))

我的Python有点生疏,但我认为这很接近。它还假设一个短(> H )是16位。

My Python is a little rusty, but I think that's close. It also assume that a short (the >H) is 16 bits.

这篇关于如何读取使用python的struct.pack方法编写的java中的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆