Reading and writing data using java nio

Above we used scanner object. With BufferedReader object we can use something like this
 try(BufferedReader dirFile = Files.newBufferedReader(dirPath)){
Complete code to write data to file is below. Please note the location is a map that contaisn Location class objects as values as seen in previous examples
public static void main(String[] args) throws IOException {
    Path locPath = FileSystems.getDefault().getPath("locations.txt");
    Path dirPath = FileSystems.getDefault().getPath("directions.txt");
    try(BufferedWriter locFile = Files.newBufferedWriter(locPath);
        BufferedWriter dirFile = Files.newBufferedWriter(dirPath)){
        for(Location location:locations.values()){
            locFile.write(location.getLocationId()+","+location.getDescription()+"\n");
                }
    }

    catch(IOException e){
        e.printStackTrace();
    }
  }
And once the data is wriiten to a file we can use static initialisation block in next example to read data from file using java nio package
 static {

    Path locPath = FileSystems.getDefault().getPath("locations.txt");
    Path dirPath = FileSystems.getDefault().getPath("directions.txt");

    try(Scanner scanner = new Scanner(Files.newBufferedReader(locPath))) {
        scanner.useDelimiter(",");
        while(scanner.hasNext()){
            int loc = scanner.nextInt();
            scanner.skip(scanner.delimiter());
            String description = scanner.nextLine();
            System.out.println("Imported description =============> "+loc+" , "+description);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
We can even read using the below method from a different file. Note here we are using a buffered reader instead of using a scanner and instead of using scanner.hasNext in while loop we are using dirFile.readLine!=null for the buffered reader object
 try(BufferedReader dirFile = Files.newBufferedReader(dirPath)){
        String input;
        while((input=dirFile.readLine())!=null){
            String[] data = input.split(",");
            int loc = Integer.parseInt(data[0]);
            String direction = data[1];
            int destination = Integer.parseInt(data[2]);
            System.out.println(loc+":"+direction+":"+destination);
            Location location = locations.get(loc);
            location.addExit(direction,destination);
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}