java socket InputStream 笔记

这是工作中遇到的时候在网上找的答案,经过自己测试符合自己想要的答案,在此做个记录,方便以后查看。

本笔记是关于在开启socket服务时的输入输出流的read()方法的正确使用。

在写网络应用中会经常这样写 :

while ((len = inStream.read(buffer)) != -1) { 
但这样往往容易发生错误或死在循环里。

解决办法:

/** 
 * @功能 读取流 
 * @param inStream 
 * @return 字节数组 
 * @throws Exception 
 */  
public static byte[] readStream(InputStream inStream) throws Exception {  
    int count = 0;  
    while (count == 0) {  
        count = inStream.available();  
    }  
    byte[] b = new byte[count];  
    inStream.read(b);  
    return b;  
}
</pre><pre name="code" class="java">还有一种读取指定长度字节的方法:<pre name="code" class="java">int count = 100;  
byte[] b = new byte[count];  
int readCount = 0; // 已经成功读取的字节的个数  
while (readCount < count) {  
    readCount += inStream.read(b, readCount, count - readCount);  
}
</pre><pre name="code" class="java">记录结束,收工。
原文出自:<a target=_blank href="http://cuisuqiang.iteye.com/blog/1434416">点击打开链接</a>  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值