inputStream.read方法阻塞解析以及读取数据不全

在开发串口通信APP时,遇到inputStream.read方法阻塞,导致无法完整读取数据的问题。尽管尝试了通过while循环判断size为-1来跳出,但在实际操作中并未奏效。read方法会阻塞直到数据可用,但串口通信(类似网络流)无法判断何时结束,不抛出异常,因此不会返回结果。之前误以为每次只读取四个字节,其实是由于PC串口助手的数据格式设置。最终解决办法是设定超时时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目前在做一个串口通信的app,过程中pc模拟单片机给开发板串口发送命令时候出现了问题,inputStream.read方法一直阻塞,完全无法读取到数据,用了网上一个方法,while判断size=-1时候跳出循环,实际上,根本不会跳出去。

read方法是这样的:

*Reads some number of bytes from the input stream and stores them into
* the buffer array <code>b</code>. The number of bytes actually read is
* returned as an integer.  This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
*
* <p> If the length of <code>b</code> is zero, then no bytes are read and
* <code>0</code> is returned; otherwise, there is an attempt to read at
* least one byte. If no byte is available because the stream is at the
* end of the file, the value <code>-1</code> is returned; otherwise, at
* least one byte is read and stored into <code>b</code>.
*
* <p> The first byte read is stored into element <code>b[0]</code>, the
* next one into <code>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值