• DemoApp.java

  • §
    package MusicLandscape;
    
    import MusicLandscape.entities.*;
    import MusicLandscape.util.formatters.CSVTrackFormatter;
    import MusicLandscape.util.io.MyTrackCSVReader;
    import MusicLandscape.util.io.MyWriter;
    
    import java.io.*;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.util.Arrays;
    
    /**
     * Test program to check MusicLandscape entity classes.
     * <p>
     * Does not do anything interesting.
     *
     * @author Jonas Altrock (ew20b126@technikum-wien.at)
     * @version 6
     * @since ExerciseSheet03
     */
    public class DemoApp {
        public static void main(String[] args) {
  • §

    Here we see how handling exceptions looks like in Java: a try-block with one or more catch-blocks. The catch-blocks can constrain the type of exception they can handle.

    We need exception handling here because the file operations in Java use what is known as checked exceptions. As soon as you write code that calls a file related function or create a reader/writer object, the IDE can tell you “hey, this might lead to an exception, please handle it”.

            try {
                MyTrackCSVReader reader = new MyTrackCSVReader(new BufferedReader(new FileReader("demo_tracks.csv")));
                MyWriter<Track> writer = new MyWriter<>(new FileWriter("output.csv"), new CSVTrackFormatter());
  • §

    My demo_tracks.csv only contains two tracks, so I just call .put(.get()) twice. The result should be a direct copy of the input file.

                writer.put(reader.get());
                writer.put(reader.get());
  • §

    Important: gotta close the files to flush the buffers.

                writer.close();
            } catch (FileNotFoundException e) {
                System.out.println("demo_tracks.csv could not be found!");
            } catch (IOException e) {
                System.out.println("IO exception: " + e.getMessage());
            }
  • §

    Afterwards, compare the two files to check if everything looks exactly the same. Here I just ignore all exceptions, because I don’t really care about the errors. That is only OK because this is an inconsequential demo application.

            try {
                byte[] input = Files.readAllBytes(Path.of("demo_tracks.csv"));
                byte[] output = Files.readAllBytes(Path.of("output.csv"));
    
                if (!Arrays.equals(input, output)) {
                    System.out.println("CSV output should be exactly equal to input!");
                }
            } catch (Exception ignored) {
            }
        }
    }