Read file into array with one line

Adding a bit to an earlier post, here is a way to read the entire contents of a data file into an array of strings using the Java Scanner library. But if you’re looking to get the entire contents into a single string, line breaks included there’s a one liner for that as well.

This just adds one more method to the end of the line of code from the previous post.

String[] ray = new Scanner(new File("data.dat")).useDelimiter("\\Z").next().split("\\n");

And now ray is an array with each element a line from data.dat.

If you’re interested in what the useDelimiter method does, it’s explained in a previous post.

Leave a Reply

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