In this Q&A, we'll go over a few options provided by Java IO APIs to read from a text file
Code below reads data from a text file, creates a list of lines and prints each element in the list
Path p = java.nio.file.Paths.get("c:/users/test.txt");
List<String> l = Files.readAllLines(p, Charset.defaultCharset());
l.forEach(System.out::println);
The above code reads all lines into memory and prints it. It works without any issues if the file is small. For large files this approach is not desirable. We can read and print iteratively as below:
Path p = java.nio.file.Paths.get("c:/users/test.txt");
Files.lines(p).forEach(System.out::println);
Notice how simple it is to read from a file. It can be done with just one or two lines of code
Comments
Post a Comment