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

Category: commons.io, viewed: 878 time(s).

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.

package org.kodejava.example.commons.io;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.FileInputStream;
import java.io.File;

public class InputStreamToString {
    public static void main(String[] args) throws Exception {
        //
        // Create an input stream for reading data.txt file content.
        //
        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.
        //
        try {
            String contents = IOUtils.toString(is, "UTF-8");
            System.out.println(contents);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats