From 67db3838608308576ef28c0259dc0584673d27a8 Mon Sep 17 00:00:00 2001 From: Clyhtsuriva Date: Fri, 11 Dec 2020 10:06:34 +0100 Subject: Getting serialization working with a song --- MusicalElement.java | 2 +- Song.java | 13 +++++++++---- jMusicHub.java | 28 ++++++++++++++++++++++++++-- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/MusicalElement.java b/MusicalElement.java index 26c3808..9dbb044 100644 --- a/MusicalElement.java +++ b/MusicalElement.java @@ -6,7 +6,7 @@ import java.io.Serializable; * Get is used to return the said value. * Set is used to modify the later.*/ -class MusicalElement implements Serializable { +public abstract class MusicalElement implements Serializable { //Our vars private int id, duration; diff --git a/Song.java b/Song.java index ecbb1eb..2890536 100644 --- a/Song.java +++ b/Song.java @@ -1,5 +1,8 @@ public class Song extends MusicalElement{ + + private static final long serialVersionUID = 2112880640160601826L; private String artist, genre; + public Song(String title, int duration, String content, String artist, Genre genre) { super(title, duration, content); this.artist=artist; @@ -12,14 +15,16 @@ public class Song extends MusicalElement{ public void setGenre(Genre genre){this.genre=genre.name();} public String toString() { - return getTitle()+";"+getDuration()+";"+getContent()+";"+artist+";"+genre; + return "Title : "+getTitle()+"\nDuration : "+getDuration()+"\nContent : "+getContent()+"\nArtist : "+getArtist()+"\nGenre : "+getGenre(); +// return getTitle()+";"+getDuration()+";"+getContent()+";"+getArtist()+";"+getGenre(); } - public void save(){ +/* public static void save(){ + String filename="songs.csv"; try { //Saving of object in a file - FileOutputStream file = new FileOutputStream(songs.csv); + FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); // Method for serialization of object @@ -36,7 +41,7 @@ public class Song extends MusicalElement{ { System.out.println("IOException is caught"); } - } + }*/ } diff --git a/jMusicHub.java b/jMusicHub.java index 2cbedc3..26fe9b6 100644 --- a/jMusicHub.java +++ b/jMusicHub.java @@ -1,4 +1,5 @@ import java.util.*; +import java.io.*; /**

jMusicHub

* @@ -120,10 +121,33 @@ public class jMusicHub { break; case "s": for (Song s: songs){ - s.save(); - } + String filename = "songs.csv"; + + // Serialization + try { + + // Saving of object in a file + FileOutputStream file = new FileOutputStream + (filename); + ObjectOutputStream out = new ObjectOutputStream + (file); + + // Method for serialization of object + out.writeObject(s); + + out.close(); + file.close(); + System.out.println("Object has been serialized\n" + + "Data before Deserialization."); + System.out.println(s); + } + catch (IOException ex) { + System.out.println("IOException is caught"); + } + } break; + default : System.out.println("Unknown command. Type h for help."); -- cgit v1.2.3