Java/Android- Convert InputStream to string
本问题已经有最佳答案,请猛点这里访问。
我正在通过蓝牙读取来自设备的持续数据流。我想知道如何将这些数据转换为字符串并打印出来?缓冲区将包含一个ASCII字符串,但当我运行它时,它会打印出整数,我希望能够看到该字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | while (true) { try { //read the data from socket stream if(mmInStream != null) { int input = mmInStream.read(buffer); System.out.println(input); } // Send the obtained bytes to the UI Activity } catch (IOException e) { //an exception here marks connection loss //send message to UI Activity break; } } |
你可以试试这个。
1 2 3 4 5 6 7 8 9 10 11 12 13 | public String isToString(InputStream is) { final int bufferSize = 1024; final char[] buffer = new char[bufferSize]; final StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(inputStream,"UTF-8"); for (; ; ) { int rsz = in.read(buffer, 0, buffer.length); if (rsz < 0) break; out.append(buffer, 0, rsz); } return out.toString(); } |