开发者社区 问答 正文

java 如何用datagramsocket 传输字符串数组

传输一个String我懂,把String转换为字符数组再传输,但是字符串数组该怎么办呢?

展开
收起
蛮大人123 2016-03-12 17:00:02 2252 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    可以把数组所有的字节拼装放入一个byte【】中传递。示例代码:

    public class Main {
        public static void main(String[] args) {
            String[] datas = {"hello","world","I"};
            try {
                //待发送的数据
                byte[] dataToSend = toByteArray(datas,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    
        public static byte[] toByteArray(String[] datas,String charset) throws UnsupportedEncodingException{
            byte[] result = new byte[0];
            if(datas==null||datas.length==0){
                return result; 
            }
    
            if(charset==null||"".equals(charset)){
                charset = "utf-8";
            }
    
            //存储数组中每个元素的byte[]字节数据
            List<byte[]> list = new ArrayList<byte[]>();
            //统计字节总长度
            int length = 0;
            for(String data:datas){
                byte[] byteArray = data.getBytes(charset);
                length+=byteArray.length;
                list.add(byteArray);
            }
    
            //将字符数组的字符串统一放入一个byte字节数组中
            result = new byte[length];
            int index = 0;
            for(int i = 0;i<list.size();i++){
                byte[] byteArray = (byte[])list.get(i);
                int byteLength = byteArray.length;
                System.arraycopy(byteArray, 0, result, index, byteLength);
                index+=byteLength;
            }
    
            return result;
        }
    }
    2019-07-17 19:01:13
    赞同 展开评论