How do I read / convert an InputStream into a String in Java? convert String to InputStream.
How do I read/convert an Input Stream into a
String in Java? convert String to Input Stream.
First, we learn What is InputStream?
The Java InputStream class, java.io.InputStream, represents an ordered stream of bytes. you can
read data from a Java InputStream as an order sequence of
bytes. Java stream is a flow of data from a source into a destination. The
source or destination can be a disk, memory, socket, or other programs. The
data can be bytes, characters, or objects.
The following way of Converting String to
InputStream.
First Solution:-
A nice way to do this is using Apache commons IOUtils to copy them InputStream into
a StringWriter... something like.
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
or
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
Second Solution:-
String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
try (
final StringWriter writer = new StringWriter();
final InputStreamReader reader = new InputStreamReader(inputStream, charset)
) {
reader.transferTo(writer);
return writer.toString();
}
}
Third Solution:-
Using ByteArrayOutputStream and inputStream.read (JDK)
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
result.write(buffer, 0, length);
while ((length = inputStream.read(buffer)) != -1) {
}
// StandardCharsets.UTF_8.name() > JDK 7
return result.toString("UTF-8");
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
or
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
Second Solution:-
String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
try (
final StringWriter writer = new StringWriter();
final InputStreamReader reader = new InputStreamReader(inputStream, charset)
) {
reader.transferTo(writer);
return writer.toString();
}
}
Third Solution:-
Using ByteArrayOutputStream and inputStream.read (JDK)
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
result.write(buffer, 0, length);
while ((length = inputStream.read(buffer)) != -1) {
}
// StandardCharsets.UTF_8.name() > JDK 7
return result.toString("UTF-8");
Comments
Post a Comment