Read a file to a string in a single line of Java

23 Jun

Rarely in my career have I written significant amounts of Java, so when I do use it I’m always learning new things.  I thought this unique way to use Scanner to read a text file into a string was great:

import java.util.Scanner;
String contents = new Scanner(new File(fileName)).useDelimiter("\\Z").next();

Nice thing about this method is that it only uses java.util.* and works in Java 1.6, 1.7 and 1.8 (possibly earlier, I haven’t verified).

Tweet about this on TwitterShare on Google+Share on FacebookShare on RedditEmail this to someoneShare on LinkedInShare on StumbleUpon

Leave a Reply

Your email address will not be published. Required fields are marked *