简体   繁体   English

Java InputStream转Python(PY4J)

[英]Java InputStream to Python (PY4J)

I'm running Java code in python using PY4J ( http://py4j.sourceforge.net/ ). 我正在使用PY4J( http://py4j.sourceforge.net/ )在python中运行Java代码。

My java function returns an InputStream and I would like to manipulate it in my python code: 我的java函数返回一个InputStream,我想在我的python代码中对其进行操作:

Java code: Java代码:

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

Python code: Python代码:

from py4j.java_gateway import JavaGateway

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

How can I get the InputStream in python? 如何在python中获取InputStream?

Should I convert it to something else in the java code before returning it to python? 我应该先将其转换为Java代码中的其他内容,然后再返回python吗?

I'm guessing you want to read from the input stream. 我猜您想从输入流中读取内容。

Java's API lets you read from an InputStream into a byte array. Java的API使您可以从InputStream读取到byte数组。 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: 没有简单的方式来传递一个Python化bytearray通过参考,但可以很容易地添加,其从读出的方法InputStream和返回一个byte数组:

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 : 然后,在Python中,您可以调用此方法从InputStream读取:

gateway = JavaGateway()
input_stream = gateway.getPCAP(key)
data = gateway.read(input_stream, 1000) # reads 1000 bytes from input_stream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM