簡體   English   中英

使用read與IOUtils.copy從InputStream中讀取

[英]Read from InputStream using read vs. IOUtils.copy

我正在嘗試使用2種方法,以便通過藍牙插槽從InputStream讀取。

第一個是:

InputStream inputStream = bluetoothSocket.getInputStream();
byte[] buffer = new byte[1024];
inputStream.read(buffer);
String clientString = new String(buffer, "UTF-8");

這個的問題是,現在在clientString中,原始消息加上“0”,直到緩沖區已滿(如果我將第一個字節用作指示符,我可以知道消息的長度,但我盡量不這樣做)。

第二個是(使用Apache Commons IO IOUtils類):

InputStream inputStream = bluetoothSocket.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
String clientString = writer.toString();

這個問題是它停留在copy線上並且永遠不會超過這一點。

所以,我的問題是,這些方法之間有什么不同,為什么我會得到不同的結果?

客戶端的代碼是(C#Using 32feet ):

client.Connect(BluetoothEndPoint(device.DeviceAddress, mUUID));
bluetoothStream = client.GetStream();                            
if (client.Connected == true && bluetoothStream != null)
{
    byte[] msg = System.Text.Encoding.UTF8.GetBytes(buffer + "\n");
    bluetoothStream.Write(msg, 0, msg.Length);
    bluetoothStream.Flush();
}

我猜IOUtils類來自Apache Commons IO。 它從inputStream復制到writer,直到它到達流的末尾(從流上的read方法返回-1)。 您的第一種方法只是嘗試讀取最多1024個字節,然后繼續。

inputStream.read(buffer)也將返回讀取的字節數。 因此,當您創建String時,您可以使用:

int read = inputStream.read(buffer);    
String clientString = new String(buffer, 0, read, "UTF-8")

您還需要檢查read方法是否返回-1,表示已到達流的末尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM