By kswaughs | Monday, June 8, 2015

How to read file into String in Java

Use Apache commons FileUtils class.

This is one of the best ways to read the contents of a file and store into String object.
It is a two lines statement code and it makes your application code more readable and better understandable.
Two static methods of FileUtils class are used and hence no object creation is required.

File file = FileUtils.getFile("path_to_file");
String content= FileUtils.readFileToString(file);

To use this class in your applications, You have to download the commons-io jar of Apache Commons Group.

Download the jar from below link.
https://commons.apache.org/proper/commons-io/download_io.cgi

To download the jar from Maven, Use below configuration in your project pom.xml file.

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>

Recommend this on


No comments:

Post a Comment