Reading an InputStream & coverting it into a String in Java?

0 votes

Suppose I have a java.io.InputStream object, how can I process it to produce a String?
Let's sat my InputStream has text data, which I need to convert into a String so that I can write it to a log file.
Can someone tell me an easy way to either read the InputStream as a String or convert it into one?

public String convertStreamToString(InputStream is) { ...... }
Oct 8, 2018 in Java by Bharani
• 4,550 points
54 views

1 answer to this question.

0 votes

Use Apache commons IOUtils and copy the InputStream into a StringWriter like this:

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

or else

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding); 

Also, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers

answered Oct 8, 2018 by DataKing99
• 8,100 points

Related Questions In Java

0 votes
2 answers

What's the best way to check if a String represents an integer in Java?

You can also use regular expression. str.matches("-?\\d+"); It will ...READ MORE

answered Aug 9, 2018 in Java by Daisy
• 8,050 points
115 views
0 votes
2 answers

How to convert a JSON String into Object in Java?

You could probably check out Google's Gson: ...READ MORE

answered 2 days ago in Java by Sirajul
• 19,670 points
256 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered 4 days ago in Java by Sirajul
• 19,670 points
112 views
0 votes
3 answers

Check if a String is numeric in Java

Java 8 Lambda Expression is used: String someString ...READ MORE

answered Sep 3, 2018 in Java by Daisy
• 8,050 points
611 views
0 votes
3 answers

How to reverse a string in java?

public static String reverse(String s) { ...READ MORE

answered Aug 16, 2018 in Java by samarth295
• 2,190 points
73 views
0 votes
2 answers
0 votes
2 answers

How do I read and convert an InputStream object to string type?

You can also use Java Standard Library ...READ MORE

answered Jul 17, 2018 in Java by Sushmita
• 6,870 points
2,824 views
0 votes
2 answers

Get all the permutations of a string in Java

You could use recursion to do this.  Try ...READ MORE

answered 2 days ago in Java by Sirajul
• 19,670 points
82 views
0 votes
2 answers

Result of character addition in Java

Binary arithmetic operations on char and byte ...READ MORE

answered 2 days ago in Java by Sirajul
• 19,670 points
45 views
0 votes
2 answers

How to convert byte array to String and STring to byte array?

The best possible way of conversion between byte[] and String is to ...READ MORE

answered 2 days ago in Java by Sirajul
• 19,670 points
50 views