Java InputStream转Python(PY4J) [英] Java InputStream to Python (PY4J)
问题描述
我正在使用PY4J在python中运行Java代码( http://py4j.sourceforge.net/ ).
I'm running Java code in python using PY4J (http://py4j.sourceforge.net/).
我的java函数返回一个InputStream,我想在我的python代码中对其进行操作:
My java function returns an InputStream and I would like to manipulate it in my python code:
Java代码:
public InputStream getPCAP(key) {
InputStream inputStream = cyberStore.getPCAP(pcapStringKey);
return inputStream;
}
Python代码:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()
input_stream = PY4J_GateWay.getPCAP(key);
...
如何在python中获取InputStream?
How can I get the InputStream in python?
在将其返回给python之前,我应该将其转换为Java代码中的其他内容吗?
Should I convert it to something else in the java code before returning it to python?
推荐答案
我猜您想从输入流中读取内容.
I'm guessing you want to read from the input stream.
Java的API使您可以从InputStream
读取到byte
数组.没有通过引用传递Pythonic bytearray
的简单方法,但是您可以轻松地添加从InputStream
读取并返回byte
数组的方法:
Java's API lets you read from an InputStream
into a byte
array. There is no simple way to pass a Pythonic bytearray
by reference, yet you can easily add a method which reads from an InputStream
and returns a byte
array:
public byte[] read(InputStream stream, int count) throws IOException {
byte[] bytes = new byte[count];
stream.read(bytes);
return bytes;
}
然后,在Python中,您可以调用此方法以读取InputStream
:
Then, in Python you can call this method to read from the InputStream
:
gateway = JavaGateway()
input_stream = gateway.getPCAP(key)
data = gateway.read(input_stream, 1000) # reads 1000 bytes from input_stream
这篇关于Java InputStream转Python(PY4J)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!