2018. 6. 28. 19:05
# Question
If you have a java.io.InputStream
object, how should you process that object and produce a String
?
Suppose I have an InputStream
that contains text data, and I want to convert it to a String
, so for example I can write that to a log file.
What is the easiest way to take the InputStream
and convert it to a String
?
public String convertStreamToString(InputStream is) {
// ???
}
# Answer
A nice way to do this is using Apache commons IOUtils
to copy the InputStream
into a StringWriter
... something like
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
or even
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
Alternatively, you could use ByteArrayOutputStream
if you don't want to mix your Streams and Writers
source: https://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
'Language > java' 카테고리의 다른 글
우분투에서 자바(Java) 설치하는 방법 (쉬워요) (0) | 2018.12.22 |
---|---|
How do I generate random integers within a specific range in Java? (0) | 2018.06.28 |
Create ArrayList from array (0) | 2018.06.28 |
Differences between HashMap and Hashtable? (0) | 2018.06.28 |