package ch.hevs.isc.slopify_v2 import java.io.{File, FileInputStream, FileOutputStream, ObjectInput, ObjectInputStream, ObjectOutputStream} object DataBaseHelper { def create(directory:String) : DataBase = { val db = new DataBase() for (a <- new File(directory).listFiles() if a.isDirectory) { val artistName = a.getName //println(s"found new artist : $artistName") val artist: Artist = new Artist(artistName) for (b <- a.listFiles() if b.isDirectory ) { val albumName = b.getName //println(s"found new album $albumName for artist : $artistName") val album: Album = new Album(albumName) for (c <- b.listFiles() if c.isFile if c.getName.toLowerCase().endsWith(".mp3") ) { val fileName = c.getName.substring(0, c.getName.length - 4) val format1 = """(\d*) (.*)""".r val format2 = """(\d*)-(\d*) (.*)""".r val format3 = """(\d*)-(.*)""".r var songName: String = "" var songNumber: Int = 0 fileName match { case format1(nr, name) => { //println(s"found song nr #$nr name:'$name' in album '$albumName' for artist : '${a.getName}'") songName = name songNumber = Integer.parseInt(nr) } case format2(cd, nr, name) => { //println(s"found song nr #$nr on cd#$cd name:'$name' in album '$albumName' for artist : '${a.getName}'") songName = name songNumber = Integer.parseInt(nr) } case format3(nr, name) => { //println(s"found song nr #$nr name:'$name' in album '$albumName' for artist : '$artistName'") songName = name songNumber = Integer.parseInt(nr) } } val song: Song = new Song(songName, songNumber) album.addSong(song) } artist.addAlbum(album) } db.addArtist(artist) } return db } def save(fileName: String, db: DataBase) : Unit = { val fos: FileOutputStream = new FileOutputStream(fileName) val oos: ObjectOutputStream = new ObjectOutputStream(fos) oos.writeObject(db) oos.close() } def load(fileName:String) : DataBase = { val fis: FileInputStream = new FileInputStream(fileName) val ois: ObjectInputStream = new ObjectInputStream(fis) val db: DataBase = ois.readObject().asInstanceOf[DataBase] ois.close() return db } def main(args: Array[String]): Unit = { val db: DataBase = create("res/songs") println(db) val artists: Array[Artist] = db.getArtists() println(artists(0)) save("res/db.bin", db) val db2: DataBase = load("res/db.bin") println(db2) val artists2: Array[Artist] = db2.getArtists() println(artists2(0)) } }