A very lean solution based on Scanner:
Scanner scanner = new Scanner( new File("poem.txt") );String text = scanner.useDelimiter("\\A").next();scanner.close(); // Put this call in a finally blockOr, if you want to set the charset:
Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" );String text = scanner.useDelimiter("\\A").next();scanner.close(); // Put this call in a finally blockOr, with a try-with-resources block, which will call scanner.close() for you:
try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) { String text = scanner.useDelimiter("\\A").next();}Remember that the Scanner constructor can throw an IOException. And don't forget to import java.io and java.util.
Source: Pat Niemeyer's blog