Java – Convert InputStream to String

Recently, i have created a simple Java Servlet server which could parse a request xml from the HTTP POST Request and then return the HTTP Response together with the response xml. In the server implementation, i need to convert an InputStream into a String. The following code shows you how to make it.

In this example, the program will read the data.txt file and print the content to the console.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ConvertInputStreamToString {
	
	public static void main(String[] args) throws IOException {
		InputStream is = null;
		StringBuilder sb = new StringBuilder();
        String line;
        
		try {
			ConvertInputStreamToString cists = new ConvertInputStreamToString();
			is = cists.getClass().getResourceAsStream("data.txt");
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            
            // Print the content of data.txt
            System.out.println(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			is.close();
		}
	}
}

 

Here is what you get after running the ConvertInputStreamToString class.

 

Done =)

Reference: Kodejava – How do I convert InputStream to String?

Leave a comment

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