Java Java Data Structures Efficiency! Custom Serialization

Jonathan Leon
Jonathan Leon
18,813 Points

When loading the txt file I get all the songs but when I quit and start the Karaoke.java again it keeps only #1 song

import com.teamtreehouse.KaraokeMachine;
import com.teamtreehouse.model.SongBook;
import com.teamtreehouse.model.SongBook;
import com.teamtreehouse.model.SongBook;

public class Karaoke {

  public static void main(String[] args) {
    SongBook songBook = new SongBook();
    songBook.importFrom("songs.txt");
    KaraokeMachine machine = new KaraokeMachine(songBook);
    machine.run();
    System.out.println("Saving book....");
    songBook.exportTo("songs.txt");
  }
}
package com.teamtreehouse.model;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Comparator;
import java.util.Map;


public class SongBook {
  private List<Song> mSongs;

  public SongBook() {
    mSongs = new ArrayList<Song>();
  }


  public void exportTo(String fileName) {


    try (
            FileOutputStream fos = new FileOutputStream(fileName);
            PrintWriter writer = new PrintWriter(fos);

        ) {
              for (Song song: mSongs) {

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

              }

          } catch(IOException ioe) {

            System.out.printf("Problem with saving %s %n", fileName);
            ioe.printStackTrace();
          }
    }


    public void importFrom(String fileName) {


          try (

                FileInputStream fis = new FileInputStream(fileName);
                BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
          ) {

            String line;
            while ((line = reader.readLine()) != null ) {

              String[] args = line.split("\\|");

              addSong(new Song(args[0],args[1],args[2]));

            }

          } catch (IOException ioe) {

            System.out.printf("There was a problem loading %s %n", fileName);
            ioe.printStackTrace();

          }


    }

  public void addSong(Song song) {
    mSongs.add(song);
  }

  public int getSongCount() {
    return mSongs.size();
  }
  //FIX ME this should be cached
  private Map<String,List<Song>> byArtist() {

    Map<String,List<Song>> byArtist = new TreeMap<>();

    for (Song song : mSongs) {

     List<Song> artistSongs = byArtist.get(song.getArtist());

      if (artistSongs == null) {

        artistSongs = new ArrayList<>();
        byArtist.put(song.getArtist(),artistSongs);

      }

        artistSongs.add(song);
    }
        return byArtist;


  }

    public Set<String> getArtists() {

      return byArtist().keySet();


    }

    public List<Song> getSongsForArtist(String artistName) {

      List<Song> songs = byArtist().get(artistName);

      songs.sort(new Comparator<Song>() {
      @Override
      public int compare(Song song1, Song song2) {

        if (song1 == song2) {
          return 0;
        }
          return song1.mTitle.compareTo(song2.mTitle);

      }

      });
        return songs;        
    }
}

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 59,156 Points

Hi Jonathan, It is quite an old question. The key is to look at the songs.txt file before and after running. The new version created by your code had all songs on one line. Thus when read back in, only the first song would make it and the rest of the line would be discarded.

Looking at your exportTo method, it is missing a training NEWLINE. Fixed here:

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

Difference of songs.txt before and after execution:

$ diff songs.txt*
1c1,15
< Michael Jackson|Beat It|https://www.youtube.com/watch?v=SaEC9i9QOvkJackson 5|I want you back|https://www.youtube.com/watch?v=G5ey0OPBxEEJackson 5|ABC|https://www.youtube.com/watch?v=oLRZZX9D7CkJourney|Don't Stop Believin'|https://www.youtube.com/watch?v=P7kDvaLUUcMWilson Phillips|Hold On|https://www.youtube.com/watch?v=UJP_mVu48OUTaylor Swift|Shake It Off|https://www.youtube.com/watch?v=-i5MU14JLdwKaty Perry|Roar|https://www.youtube.com/watch?v=uFmocJG1ipARitchie Valens|La Bamba|https://www.youtube.com/watch?v=vvB6RKJAwpMU2|With Or Without You|https://www.youtube.com/watch?v=Ws0mDfYd8UQU2|I Still Haven't Found|https://www.youtube.com/watch?v=0po5HpEoAS4Jackson 5|Rockin' Robin|https://www.youtube.com/watch?v=sbk_g0NR-NUThe Cure|Friday I'm in Love|https://www.youtube.com/watch?v=GMw2Jp4GnCIThe Cure|Boys Don't Cry|https://www.youtube.com/watch?v=5lZpc1KReksThe Cure|Just Like Heaven|https://www.youtube.com/watch?v=pZxIyvsZlPkThe Cure|Love Song|https://www.youtube.com/watch?v=ogi6aMOYOEQ
\ No newline at end of file
---
> Michael Jackson|Beat It|https://www.youtube.com/watch?v=SaEC9i9QOvk
> Jackson 5|I want you back|https://www.youtube.com/watch?v=G5ey0OPBxEE
> Jackson 5|ABC|https://www.youtube.com/watch?v=oLRZZX9D7Ck
> Journey|Don't Stop Believin'|https://www.youtube.com/watch?v=P7kDvaLUUcM
> Wilson Phillips|Hold On|https://www.youtube.com/watch?v=UJP_mVu48OU
> Taylor Swift|Shake It Off|https://www.youtube.com/watch?v=-i5MU14JLdw
> Katy Perry|Roar|https://www.youtube.com/watch?v=uFmocJG1ipA
> Ritchie Valens|La Bamba|https://www.youtube.com/watch?v=vvB6RKJAwpM
> U2|With Or Without You|https://www.youtube.com/watch?v=Ws0mDfYd8UQ
> U2|I Still Haven't Found|https://www.youtube.com/watch?v=0po5HpEoAS4
> Jackson 5|Rockin' Robin|https://www.youtube.com/watch?v=sbk_g0NR-NU
> The Cure|Friday I'm in Love|https://www.youtube.com/watch?v=GMw2Jp4GnCI
> The Cure|Boys Don't Cry|https://www.youtube.com/watch?v=5lZpc1KReks
> The Cure|Just Like Heaven|https://www.youtube.com/watch?v=pZxIyvsZlPk
> The Cure|Love Song|https://www.youtube.com/watch?v=ogi6aMOYOEQ