Reading and writng objects to a file using nio in java

   try (ObjectOutputStream locfile = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("locations2.dat")));) {
   try(ObjectOutputStream locFile  =  new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(locPath)))){

Compelete code to write objects to a file

   public static void main(String[] args) throws IOException {
       Path locPath = FileSystems.getDefault().getPath("locations.dat");
       try(ObjectOutputStream locFile  =  new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(locPath)))){
               for (Location location : locations.values()) {
                   locFile.writeObject(location);
               }
           }
       catch(IOException e){
           e.printStackTrace();
       }
   }

Same way for reading data in static initialization block we pass instance of Path instead of instance of File like below

Path locPath = FileSystems.getDefault().getPath("locations.dat");
try (ObjectInputStream locfile = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(locPath)))) {

Compelete code is below

 static {
   Path locPath = FileSystems.getDefault().getPath("locations.dat");
   try (ObjectInputStream locfile = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(locPath)))) {
           boolean endOfFile = false;
           while (!endOfFile) {
               try {
                   Location location = (Location) locfile.readObject();
                   //And once object is created we can access the methods of this class
                   System.out.println("Read location---> " + location.getLocationId() + " , " + location.getDescription());
               } catch (EOFException e) {
                   endOfFile = true;
               }
           }
       }
       catch (InvalidClassException e) {
           System.out.println("Invalid class exception  ->"+e.getMessage());
       }
       catch (IOException e) {
           System.out.println("IO exception  ->"+e.getMessage());
       }
       catch (ClassNotFoundException e) {
           System.out.println("Invalid class exception  ->"+e.getMessage());
       }
   }