We can use the code below to convert the content of an InputStream
into a String
. At first, we use FileInputStream
create to a stream 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.
package org.kodejava.commons.io;
import org.apache.commons.io.IOUtils;
import java.io.InputStream;
import java.io.FileInputStream;
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("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
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.14.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a table with multiple header in iText 8? - March 16, 2024
- How do I add Image to a Table in iText 8? - March 11, 2024
- How do I downgrade Android SDK emulator version? - February 12, 2024