如何合并2个ByteBufs?

时间:2018-09-03 11:43:00

标签: java netty

我正在尝试将2个ByteBuf合并为一个ByteBuf,我该怎么做?

private string getLocationByGeoLocation(string longitude, string latitude)
    {
        string locationName = string.Empty;

        try
        {
            if (string.IsNullOrEmpty(longitude) || string.IsNullOrEmpty(latitude))
                return "";

            string url = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false", latitude, longitude);


            WebRequest request = WebRequest.Create(url);

            using (WebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    DataSet dsResult = new DataSet();
                    dsResult.ReadXml(reader);
                    try
                    {
                        foreach (DataRow row in dsResult.Tables["result"].Rows)
                        {
                            string fullAddress = row["formatted_address"].ToString();
                        }
                    }
                    catch (Exception)
                    {

                    }

                }
            }
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }


        return locationName;
    }

上面的代码会打印

  

[33,44,55,66,77,88,99,22]

     

[77,88,99,22]

我可以轻松合并字节数组,但是我无法合并ByteBufs,我无法调用ByteBuf.array()方法并在生产中使用合并的字节数组创建新的ByteBuf(我调用时得到import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.apache.commons.lang3.ArrayUtils; import java.util.Arrays; public class Main { public static void main(String[] args) { ByteBuf a = Unpooled.buffer(4).writeByte(33).writeByte(44).writeByte(55).writeByte(66); ByteBuf b = Unpooled.buffer(4).writeByte(77).writeByte(88).writeByte(99).writeByte(22); byte[] byteArray = new byte[4]; a.readBytes(byteArray); System.out.println(Arrays.toString(ArrayUtils.addAll(byteArray, b.array()))); System.out.println(Arrays.toString( Unpooled.copiedBuffer(a, b).array() )); } } UnsupportedOperationException: direct buffer如此

1 个答案:

答案 0 :(得分:2)

发生这种情况是因为您的代码已经读取了a的所有四个字节:

a.readBytes(byteArray);

此时a的读取索引已超出数据结尾,因此不会复制其任何字节。

在读取之前放置用于复制缓冲区的代码即可解决此问题:

System.out.println(Arrays.toString(
        Unpooled.copiedBuffer(a, b).array()
));
byte[] byteArray = new byte[4];
a.readBytes(byteArray);
System.out.println(Arrays.toString(ArrayUtils.addAll(byteArray, b.array())));

或者,您可以在a.resetReaderIndex()之后调用readBytes,以将缓冲区“倒回”到开头。

相关问题