如何将字节数组转换为字符串?

时间:2015-02-19 12:50:36

标签: java android bluetooth

我试图将字节转换为字符串,从蓝牙设备读取后我得到的字符串。下面是我正在使用的代码,但它没有给出正确的字符串。 输出就像这样

02-19 18:01:49.300:I / BluetoothReadService(17693):消息读取:���8��1.04TTO��������������������

byte[] buffer = new byte[1024];
            int bytes;
            // Keep listening to the InputStream while connected
            while (true)
            {
                try
                {
                    // Read from the InputStream                    
                    bytes = mmInStream.read(buffer, 0, buffer.length);

                    String readMessage = null;
                    byte[] getBytes = null;
                    try {
                        readMessage = BitConverter.toString(buffer);
                        getBytes = BitConverter.getBytes(readMessage);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    String s = new String(getBytes, "US-ASCII");
                    Log.i(TAG, "Message Read : "+readMessage +"ByteString"+s);
                    mHandler.obtainMessage(MainActivity.MESSAGE_READ).sendToTarget();
                } catch (IOException e)
                {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }

请建议做什么?

6 个答案:

答案 0 :(得分:0)

readMessage String应以不同的方式初始化。 如果您使用readMessage = new String(buffer);,它应该有效。

答案 1 :(得分:0)

apache StringUtils,您可以使用此方法from document

 public static String newStringUsAscii(final byte[] bytes) {
    return new String(bytes, Charsets.US_ASCII);    
  }

如果问题仍然存在,请使用以下方法来读取字符串

public String readData() {

    String response = null;
    int bytesReceived=-1;
    byte[] readBuffer = new byte[1024];
    try{

        try{
            bytesReceived = inputStream.read(readBuffer);
            Logger.debugLog(MODULE ,"# Byte Receieved #" + bytesReceived);
        }catch(Exception e){
            Logger.errorLog(MODULE ,"Error in readData() , Reason:"+e.getMessage(),e);

        }
        if(bytesReceived > 0){          
            response = new String(readBuffer,0,bytesReceived);

            Logger.debugLog(MODULE + "Total Bytes Received: " + bytesReceived);
            Logger.debugLog(MODULE, "Total Time Taken : " + timetoread);
            Logger.debugLog(MODULE, "Length of data received : " + response.length());
            Logger.infoLog(MODULE, "Data Received : ####" + response + "####");
        }else{
            ////////// HERE MEANS TCP CONNECTION STATUS WILL CLOSE_WAIT
            ////////// SO RELEASING CONNECTION.
            Logger.infoLog(MODULE, " Releasing Resource. bytesReceived is <= 0 : Total Bytes Received :"+ bytesReceived );

                releaseResources();

            }
            Logger.infoLog(MODULE, " Resource has been released.");
        }
    }catch(Exception e){
        Logger.errorLog(MODULE, "In catch : Data Received : ####" + response + "####");
        Logger.errorLog(MODULE, "Exception in readdata() : " + e);
    }finally{
        readBuffer=null;
    }
    return response;
}

答案 2 :(得分:0)

我认为不是

String s = new String(getBytes, "US-ASCII");

你应该使用

String s = new String(buffer, "US-ASCII");

并使用BitConverter删除该部分。

答案 3 :(得分:0)

您似乎忽略了实际读取的字节数,并从1024字节的整个缓冲区中创建了新的字符串。

请改为尝试:

String readMessage = new String(buffer, 0, bytes, "US-ASCII");

答案 4 :(得分:0)

BluetoothChatFrangment.java中阅读Android官方Bluetooth Chat example,您会看到:

// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
在此示例中,

msg.arg1在您的情况下等于bytesreadBuf byte[]也是{{1}}。

答案 5 :(得分:0)

这应该为您完成工作。

String s = new String(buffer, StandardCharsets.UTF_8)

在KitKat上需要Api。