Reading Data From a File using Java NIO
Jun 27, 2020
Make sure to subscribe to our newsletter and be the first to know the news.
Jun 27, 2020
Make sure to subscribe to our newsletter and be the first to know the news.
In this tutorial we are going to learn how to read data from file using Java NIO classes of Path and Files, if you are not aware of the methods available with these classes click here.
Steps are very Simple.
Create a Path Object pointing to the file and then use the readAllLines() of Files to read the data from the file.
import java.nio.file.*;
import java.util.*;
public class ReadFile
{
public static void main(String[] args)
{
try
{
Path path=Paths.get("data.txt");
List data= Files.readAllLines(path);
for(String line:data)
{
System.out.println(line);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}