Read a File into a String using a single statement

Writing by on Monday, 18 of November , 2013 at 6:08 am

I’ve found that java.util.Scanner class instead of the java.io classes to work well for most of my text file reading and parsing needs.

String content = new Scanner(new File("/path/to/file.txt")).useDelimiter("\\Z").next();
System.out.println(content);

For more info read up natch3z or coderwall.

Leave a comment

Category: Java

Shivdev Kalambi's Blog

Shivdev Kalambi is a Software Development Manager, previously a Principal Software Engineer at ArcSight/HP. With over 16 years' experience in software development, he's worked on several technologies and played different roles and contributed to all phases of projects. Non-tech activies include Ping-pong, Rock Climbing and Yoga at PG, Golf, Skiing, Swimming & a beer enthusiast.