问题
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