java

How to convert InputStream object to String in Java

It is often necessary to convert an InputStream object into a string, for example, to read data from a file or a network socket.
 

Read InputString in String bytewise

An InputStream is a stream of bytes. The easiest method is to read the bytes and convert them into a string.

private static String toStr(InputStream is) throws IOException {
    byte[] buffer = new byte[1024];
    StringBuilder sb = new StringBuilder();
    int length = 0;

    while ((length = is.read(buffer)) >= 0) {
        sb.append(new String(Arrays.copyOfRange(buffer, 0, length), "UTF-8"));
    }

    return sb.toString();
}

First, the variables are declared and initialized. The byte array buffer serves as a buffer for the bytes that have been read from the InputStream. The StringBuilder is used to combine the individual strings that have been read. The variable-length saves the bytes that have been read each time.

The expression (length = is.read (buffer)) > = 0 does two things at once: it assigns the number of bytes that have been read to the variable length and then compares whether the length is greater than or equal to 0. The read(byte[] buffer) method returns the value -1 when the stream has ended.

Finally, the concatenated value of the StringBuilder is returned.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More

 

Reading InputStream with a Reader

This method uses an InputStreamReader to read the data from the InputStream.

private static String toStr(InputStream is) throws IOException {
    InputStreamReader isr = new InputStreamReader(is, Charset.forName("UTF-8"));
    char[] buffer = new char[1024];
    StringBuilder sb = new StringBuilder();
    int length = 0;

    while ((length = isr.read(buffer, 0, buffer.length)) >= 0) {
        sb.append(buffer, 0, length);
    }
    isr.close();

    return sb.toString();
}

The advantage here is that a new string does not have to be created every time the loop is run, but the chars that have been read are appended to the StringBuilder.
 

InputStream to String with Guava

As so often, Google Guava does the work for us. Here is the solution in one line:

private static String toStr(InputStream is) throws IOException {
    return new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8);
}

The static method ByteStreams.toByteArray(is) returns a byte array with which we can easily create a new string and return it.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *