Java InputStream to Python (PY4J)

℡╲_俬逩灬. 提交于 2020-06-26 14:06:57

问题


I'm running Java code in python using PY4J (http://py4j.sourceforge.net/).

My java function returns an InputStream and I would like to manipulate it in my python code:

Java code:

public InputStream getPCAP(key) {
        InputStream inputStream = cyberStore.getPCAP(pcapStringKey);
        return inputStream;
}

Python code:

from py4j.java_gateway import JavaGateway

gateway = JavaGateway()
input_stream = PY4J_GateWay.getPCAP(key); 
...

How can I get the InputStream in python?

Should I convert it to something else in the java code before returning it to python?


回答1:


I'm guessing you want to read from the input stream.

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;
}

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


来源:https://stackoverflow.com/questions/25891144/java-inputstream-to-python-py4j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!