How do I get the content of an InputStream as a String?

We can use the code below to convert the content of an InputStream into a String. At first we use FileInputStream create to a connection to a file that going to be read. IOUtils.toString(InputStream input, String encoding) method gets the content of the InputStream and returns a string representation of it. In the end we need to close the InputStream in a finally block.




public class InputStreamToString {
    public static void main(String[] args) throws Exception {
        // Create an input stream for reading data.txt file content.
        try (InputStream is = new FileInputStream(new File("data.txt"))) {
            // Get the content of an input stream as a string using UTF-8
            // as the character encoding.
            String contents = IOUtils.toString(is, "UTF-8");

Maven Dependencies

<!-- -->

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.