Java Java Data Structures Efficiency! Custom Serialization

Matthew Francis
Matthew Francis
6,967 Points

Newbie - Serialization, Why not use system.out.printf() instead of PrintWriter.printf()?

  public void exportTo(String fileName){
    try(
      fileOutputStream fos = new FileOutputStream(fileName);
      PrintWriter writer = new PrintWriter(fos);//PrintWriter prints formatted representations of objects to a text-output stream., 
                                                  we used ToString(), so printWriter works
    ){
      for(Song song : mSongs){
        writer.printf("%s|%s|%s %n", song.getArtist(), song.getTitle(). song.getVideoUrl());
       //Why not use system.out.printf()? Why use PrintWriter.printf()?
      }
    }catch(IOException ioe){
      System.out.printf("Problem saving %s %n", fileName);
      ioe.printStacktrace();
    }
  }

3 Answers

Alexander Nikiforov
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,137 Points

Because writer.printf writes to file(with all syntax above), whereas system.out.printf writes to console. Different printf-s for different purposes.

Matthew Francis
Matthew Francis
6,967 Points

Thanks, one question though, why do you want to write it to a file? I'm guessing it's something relating to serialization/deserilization?

Alexander Nikiforov
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,137 Points

No I think, no serialization here. when you write:

writer.printf("%s|%s|%s %n", song.getArtist(), song.getTitle(). song.getVideoUrl());

All you get: is simple line "Artist|Title|VideoUrl" in file. Text file.

If you want to save something using serialization, then you have to use the code, like here:

http://www.tutorialspoint.com/java/java_serialization.htm

import java.io.*;

public class SerializeDemo
{
   public static void main(String [] args)
   {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;

      try
      {
         FileOutputStream fileOut =
         new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }
   }
}

You see how ObjectOutputStream is used. I haven't tried that myself, but I do believe this code, and in the video, Crais save files just as text

Colby Wise
Colby Wise
3,165 Points

Alexander - so to help me break this down into layman's terms: you use serialization to [read / write] text files / data? Or what's the big idea or purpose for it. What are the benefits of someone implementing serialization?

Colby Wise
Colby Wise
3,165 Points

As always, thanks AN