Java/Android- Convert InputStream to string [duplicate]
Asked Answered
M

1

6

I am reading a constant stream of data coming from a device via Bluetooth. I'm wondering how I can convert this data to a string and print it out? The buffer will contain an ASCII string but when I run it it prints out integers, i would like to be able to see the string.

 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;
                }
            }
Mauro answered 25/5, 2018 at 17:57 Comment(1)
You should print the contents of that buffer to begin with. Further you should have told us what is readed. What will the buffer contain?Sacerdotal
S
5

you can try this.

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();
    }
Starobin answered 25/5, 2018 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.