How do I read / convert an InputStream into a String in Java?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Java, you can read or convert an InputStream into a String using various approaches. Here are some of the most common methods:
1. Using BufferedReader and InputStreamReader
This method involves wrapping the InputStream with an InputStreamReader, then wrapping that with a BufferedReader. This approach allows you to read the InputStream line by line and concatenate the result into a single String.
2. Using Scanner
The Scanner class can also be used to convert an InputStream to a String. This method is more concise, but it may be slightly less efficient for large streams.
useDelimiter("\\A"): This tells theScannerto use the beginning of the input as the delimiter, effectively reading the entire input as a single string.
3. Using ByteArrayOutputStream
You can read the bytes from the InputStream and then convert them into a String using a ByteArrayOutputStream. This method is especially useful when you are dealing with binary data or want more control over character encoding.
toString("UTF-8"): Specifies the character encoding to use when converting the bytes to a string.
4. Using Streams (Java 8+)
If you're using Java 8 or later, you can leverage the Streams API to convert an InputStream to a String in a single line:
Summary
- BufferedReader and InputStreamReader: Good for line-by-line reading.
- Scanner: Concise and simple for quick conversions.
- ByteArrayOutputStream: Offers more control, especially for binary data.
- Java 8 Streams: Modern and elegant, best if you're working with Java 8 or newer.
Choose the method that best suits your needs based on your specific use case and the environment you're working in.
Related reading
- Java, How to get number of messages in a topic in apache kafka
- What is the difference between public, protected, package-private and private in Java?
- / and / in Java Comments
- (double colon) operator in Java 8
- Plus sign not encoded with RestTemplate using String URL, interpreted as space
- a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found
- A default binder has been requested, but there are no binders available for ''org.springframework.cloud.stream.messaging.DirectWithAttributesChannel''
- A failure occurred while executing com.android.build.gradle.internal.tasks

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.