Skip to content

Read a file into a String with one line

This is one of those that I never remember, but use a lot whenever I want to pull an entire file into a String quickly.

String text = new Scanner(new File("file.txt")).useDelimiter("\\A").next();

\\A is the start of the file, so Scanner is going to try and split on the beginning of the file. Since there’s only one beginning, there’s only one next.

Published inCode Tips

Be First to Comment

Leave a Reply

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