Java 7 read file to String

Before Java7, reading a file in Java and convert to a String, used to require a lot of code either using FileInputStream or BufferReader with looping conditions. Of course, we might have used this by writing as a Utility method or using util methods from Apache Commons or Google Collections.

Java 7 comes with a new approach to read files to String in one-liner code, simplifying the hassles of looping and terminating conditions so forth. Actual code to do this is

String fileContent= new String(readAllBytes(get(“test.txt”)));

java 7 read file to string: source code for the above.

Source code

package com.jminded.java7.nio;
import static java.lang.System.out;
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * 
 * @author Umashankar
 * https://jminded.com
 */
public class ReadFileToString {

	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		// TODO Auto-generated method stub
		//readAllBytes -Files.readAllBytes  and get - Paths.get are static imports
		out.println(new String(readAllBytes(get("websites.txt"))));
		
		Path path=Paths.get("websites.txt");
		byte[] contents=Files.readAllBytes(path);
		String fileContent =new String(contents);
		out.println(fileContent);
	}
}

Output

JMinded.com|CodingBuffer.com|J2eedev.com

0 thoughts on “Java 7 read file to String”

Leave a Comment