java 使用 read 与 IOUtils.copy 从 InputStream 读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26914404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:51:53  来源:igfitidea点击:

Read from InputStream using read vs. IOUtils.copy

javaandroidsocketsbluetooth

提问by SharonKo

I'm trying to use 2 approaches in order to read from InputStreamvia Bluetooth socket.

我正在尝试使用 2 种方法来InputStream通过蓝牙套接字进行读取。

The first one is:

第一个是:

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

The problem with this one is that now in clientStringthere's the original message plus "0" until the buffer is full (I can know the length of the message if I'll use the first bytes as indicators but I try not to).

这个问题是,现在clientString有原始消息加上“0”,直到缓冲区已满(如果我将使用第一个字节作为指示符,我可以知道消息的长度,但我尽量不这样做)。

The second one is (Using IOUtilsclass from Apache Commons IO):

第二个是(使用IOUtils来自 的类Apache Commons IO):

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

The problem with this one is that it stays on the copyline and never continue beyond this point.

这个的问题在于它保持copy在线并且永远不会超过这一点。

So, my question is, what is the different between those approaches and why do I get different results?

所以,我的问题是,这些方法之间有什么不同,为什么我会得到不同的结果?

The code on the client side is (C# Using 32feet):

客户端的代码是(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();
}

采纳答案by Zoran Regvart

I'm guessing that IOUtils class is from Apache Commons IO. It copies from inputStream to writer until it reaches the end of the stream (-1 is returned from read method on stream). Your first method just tries to read the maximum of 1024 bytes and then proceeds.

我猜 IOUtils 类来自 Apache Commons IO。它从 inputStream 复制到写入器,直到它到达流的末尾(从流上的 read 方法返回 -1)。您的第一种方法只是尝试读取 1024 字节的最大值,然后继续。

Also the inputStream.read(buffer) will return the number of bytes read. So when you create your String you can use that:

此外 inputStream.read(buffer) 将返回读取的字节数。因此,当您创建 String 时,您可以使用它:

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

You also need to check if the read method returns -1 indicating that the end of the stream is reached.

您还需要检查 read 方法是否返回 -1 表示已到达流的末尾。