Lesson 11

Serialisation

Sometimes reading row by row is not enough.

I. Save data to file


Task 0

Add a new dependency:


<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.10.4</version>
</dependency>
Task 1

Create a new POJO named Song with fields: title (String), subtitle (String), author (String), year (Integer), image (String) and MusicLibrary with one field: list of songs (List<Song>).

Task 2

Take a look on WriteDataToFile. Write the method musicLibraryToFile, that saves a given object to a file given in second argument.


public class WriteDataToFile {

    public static void main(String[] args) throws IOException {
        List<Song> songs = new ArrayList<>();
        songs.add(new Song("Stayin' alive", "A, a, a, a, stain' alive!", "Bee Gees", 1977, "https://static.stereogum.com/uploads/2019/11/The-Bee-Gees-Stayin-Alive-1574874474-800x536.jpg"));
        songs.add(new Song("Killing Me Softly With Her Song", "Take It Easy", "Perry Como", 1990, "https://ecsmedia.pl/c/killing-me-softly-with-her-song-w-iext53741608.jpg"));
        songs.add(new Song("Hotel California", " Live at the Summit, Houston, Texas", "Eagles", 1976, "https://image.ceneostatic.pl/data/products/56635000/i-the-eagles-hotel-california-40th-anniversary-remastered-edition-cd.jpg"));
        songs.add(new Song("Rainbow in the Dark", "When I see lightning, you know it always brings me down", "Dio", 1983, "https://i.pinimg.com/736x/0a/97/ff/0a97ff3a726843248d3603e4777e6840.jpg"));

        MusicLibrary musicLibrary = new MusicLibrary(songs);
        musicLibraryToFile(musicLibrary, "data.xml");
    }
}                    
                
Task 3

Do opposite operation in class ReadDataFromFile. You have to read data from the file from previous task.


public class ReadDataFromFile {

    public static void main(String[] args) throws IOException {
        MusicLibrary musicLibrary = readMusicLibraryFrom("data.xml");
        for (Song s: musicLibrary.getSongs()) {
            System.out.println(s);
        }
    }
}                  
                
Task 4

Prepare .fxml view with a VBox wrapped in ScrollPane. Set value of fx:id for vbox and create a variable for it.

Task 5

In initialize method of controller use ReadDataFromFile.readMusicLibraryFrom("data.xml") for receiving music library. Next create components to display songs in vbox.

Efekt końcowy lekcji 11: Biblioteka muzyczna

Preview of a final effect