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;
import java.nio.charset.StandardCharsets;
public class InputStreamToString {
public static void main(String[] args) throws Exception {
// Create an input stream for reading data.txt file content.
try (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.
String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
System.out.println(contents);
}
}
}
Maven Dependencies
<!-- http://repo1.maven.org/maven2/commons-io/commons-io/2.6/commons-io-2.6.jar -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020