從Socket中讀取指定長度資料問題

2021-09-01 05:04:15 字數 1000 閱讀 1227

inputstream is = .....

...................

byte bs = new byte[10];

int readed = is.read(bs);

is.close();

我們知道上面的**可以從輸入流裡讀取readed個位元組的資料(readed範圍為-1到10),readed==-1表示流已讀完,那麼什麼時候會出現readed為0-9的情況呢?

答案:輸入流中剩餘內容不足10個位元組(如is為fileinputstream表示檔案剩餘內容不足10個位元組)

但對於套接字讀取我們要注意,**如下:

inputstream is = socket.getinputstream();

is.read...

....

byte bs = new byte[10];

is.read(bs);

string a=new string(bs);

byte bs2 = new byte[60];

is.read(bs2);

string b=new string(bs2);

上面對例子表示從套接字中接收資料,先接收10個位元組的字段a,然後再接收60個位元組的字段b,但實際is.read(bs)卻有可能讀取的資料不足10個位元組,從而導致is.read(bs2)的時候卻讀到了字段a的一部分資料,這樣就出錯了,所以理論上上面這種寫法是不正確不嚴謹的(小資料時也許在大多數情況下沒問題,但不能保證一定沒問題)。

對於套接字讀取需要這樣寫:

// 從套接字緩衝區is中讀取length長度的資料

private byte recvbytes(inputstream is, int length) throws ioexception finally

}return ret;

}byte bs = recvbytes(is, 10);

byte bs2 = recvbytes(is, 60);

從InputStream中讀取特定長度的資料

public static final int read buffer size 1024 讀取流中的字元到陣列 param in 該方法執行完成不會關閉流 param limit 讀取大小限制 return throws ioexception public static byte readstr...

Java實現位元組陣列中擷取指定長度陣列元素

本文使用system提供的乙個靜態方法arraycopy 實現陣列間的複製。public static native void arraycopy object src,int srcpos,object dest,int destpos,int length src 源陣列 srcpos 源陣列要...

比較方便的生成指定長度數字和字母混合的隨機數

namespace netcms.common 生成隨機數字 生成長度 是否要在生成前將當前執行緒阻止以避免重複 public static string number int length,bool sleep return result 生成隨機字母與數字 生成長度 public static ...