DEV Community

Cover image for Read text file in java
CoderLegion
CoderLegion

Posted on • Edited on • Originally published at kodblems.com

Read text file in java

🎉 Before you dive into this article...

🚀 Check out our vibrant new community at CoderLegion.com!

💡 Share your knowledge, connect with like-minded developers, and grow together.

👉 Click here to join now!

There are methods to simply retrieve lines from a file. It is also possible to do more advanced processing depending on the data it contains.

Java
The Java language contains several possibilities for reading a text file. There are methods to simply retrieve the lines from the file. It is also possible to do more advanced processing depending on the data contained in a file. If the file contains numbers, it is possible to transfer them to an integer array.

The Files class is used in the Java language to manage files. It contains the ReadAllLines () method which reads all the lines from the file and transfers them to a string array. If your file contains only integers separated by spaces, you must then use a regular expression to decompose each line into a list of numbers.

Split () method
The split () method splits a character string following a regular expression. We are going to use the \ s character class, which indicates a space character (space, line feed, tabulation) and the + quantifier, to indicate that there can be one or more between the integers. The split () method returns strings. The Integer.valueOf () method converts each string to an integer.

List numbers = new ArrayList <> (); for (String line: Files.readAllLines (Paths.get (/path/to/myFile.txt))) { for (String string: line.split (\ s +)) { Integer integer = Integer.valueOf (string); numbers.add (integer); } }
The Java 8 language provides streams, which allow collections of objects to be transferred directly from one method to another without storing them in memory. The map () method will transfer the contents as an array to the next method. The flatMap () method is used between the method that separates rows into multiple strings and the method that turns strings into integers. Before this method, we have an array (the rows) that contains arrays of strings (the strings separated by the regular expression). This method will transform this two-dimensional array into a one-dimensional array containing all the strings to be transformed into an integer. Finally, the collect () method stores the result of transforming entire strings in the integer list.

List numbers = Files.lines (Paths.get (/path/to/myFile.txt))
.map (line -> line.split (\ s +)). flatMap (Arrays :: stream)
.map (Integer :: valueOf)
.collect (Collectors.toList ());

Top comments (0)