gpt4 book ai didi

java - 重新分配输入/输出流?

转载 作者:行者123 更新时间:2023-11-30 03:52:53 25 4
gpt4 key购买 nike

我正在尝试使用 android 中的库连接到终端仿真器,这将连接到串行设备并且应该显示发送/接收的数据。要附加到终端 session ,我需要向 setTermIn(InputStream) 提供一个 inputstream 并向 setTermOut(OutputStream)< 提供一个 outputstream/.

我在 onCreate() 中初始化并附加了一些流,这些只是初始流,没有附加到我想要发送/接收的数据。

private OutputStream bos;
private InputStream bis;

...

byte[] a = new byte[4096];
bis = new ByteArrayInputStream(a);
bos = new ByteArrayOutputStream();
session.setTermIn(bis);
session.setTermOut(bos);
/* Attach the TermSession to the EmulatorView. */
mEmulatorView.attachSession(session);

我现在想在发送和接收数据时将流分配给数据,但我认为我做错了。在每次按下回车键时调用的 sendData() 方法中,我有:

public void sendData(byte[] data)
{
bos = new ByteArrayOutputStream(data.length);
}

并且在 onReceiveData() 方法中,每次通过串行接收数据时调用:

public void onDataReceived(int id, byte[] data)
{
bis = new ByteArrayInputStream(data);
}

我在我的终端屏幕上没有看到任何数据,但我通过串口成功地发送和接收了它。所以我的问题是,我应该在每次发送和接收数据时都设置流还是只设置一次。我还需要将它们再次附加到终端 session mEmulatorView.attachSession(session) 某处还是应该将新流自动发送到屏幕?

我的理论是我的终端连接到旧的流,这就是我在终端屏幕上看不到数据的原因。这是正确的吗?

我尝试使用 boolean 值和 if 语句在每个方法中设置新的输入/输出流一次,但随后我在 logcat 中收到警告消息

RuntimeException '向死线程上的处理程序发送消息'

我已经根据回答将其编辑为 write 和 rad,但我注意到该库有它自己的 write 方法来将数据提供给终端,所以我什至不知道流的用途是什么案例,我需要这个写入来写入模拟器吗?

public void write(byte[] data,
int offset,
int count)
Write data to the terminal output. The written data will be consumed by the emulation client as input.
write itself runs on the main thread. The default implementation writes the data into a circular buffer and signals the writer thread to copy it from there to the OutputStream.

Subclasses may override this method to modify the output before writing it to the stream, but implementations in derived classes should call through to this method to do the actual writing.

Parameters:
data - An array of bytes to write to the terminal.
offset - The offset into the array at which the data starts.
count - The number of bytes to be written.

最佳答案

Java 中的对象是通过引用传递的,因此如果您这样做

bos = new ByteArrayOutputStream(data.length)

您实际上是在丢弃以前的输出流并创建一个新输出流。

尝试保持对输入和输出流的引用并将数据写入其中,例如:

bos.write(data);

关于java - 重新分配输入/输出流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13878768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com