adam bien's blog

Reading A File Into A String - With A Single Line And JDK 1.6+ 📎


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerSample {

    public static void main(String[] args) throws FileNotFoundException {
     //Z means: "The end of the input but for the final terminator, if any"
        String output = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
        System.out.println("" + output);
    }
}


[Thanks Paulo Silveira for the snippet!]