code: public static void writeObjectToFile(String path, Object toWrite, SparkContext sc) throws IOException {
          FileSystem fileSystem = FileSystem.get(sc.hadoopConfiguration());
          try (BufferedOutputStream bos = new BufferedOutputStream(fileSystem.create(new Path(path)))) {
              ObjectOutputStream oos = new ObjectOutputStream(bos);
              oos.writeObject(toWrite);
          }
      }
docs: Write an object to HDFS (or local) using default Java object serialization
  
  @param path    Path to write the object to
  @param toWrite Object to write
  @param sc      Spark context