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 block
Or, 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 block
Or, 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