In this example we use FileUtils
class from Apache Commons IO to read the content of a file. FileUtils
have two static methods called readFileToString(File)
and readFileToString(File, String)
that we can use.
An example to read file contents and return the result as a string can be seen below.
package org.kodejava.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class ReadFileToStringSample {
public static void main(String[] args) {
// Here we create an instance of File for sample.txt file.
File file = new File("README.md");
try {
// Read the entire contents of sample.txt
String content = FileUtils.readFileToString(file, "UTF-8");
System.out.println("File content: " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023