forked from chobeat/scala-game-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileSave.scala
92 lines (80 loc) · 2.4 KB
/
FileSave.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package sgl
package awt
import scala.io.Source
/** Implement Save with a standard file */
class FileSave(filename: String) extends AbstractSave {
//TODO: should make this a generic putX[X], and it should take
// some implicit param to get the type and have the type info being
// part of the serialization, to make sure we don't parse back Int as String
override def putString(name: String, value: String): Unit = {
val rawLines: List[String] = try {
Source.fromFile(filename).getLines().toList
} catch {
case (_: Exception) => List()
}
val parsedLines: List[(String, String)] = rawLines.flatMap(line => try {
val Array(n, v) = line.split(":")
Some(n -> v)
} catch {
case (_: Exception) => None
})
val newLines: List[(String, String)] =
if(parsedLines.exists(_._1 == name))
parsedLines.map{ case (n, v) =>
if(n == name)
(n, value.toString)
else
(n, v)
}
else
(name, value.toString) :: parsedLines
val out = new java.io.PrintWriter(filename, "UTF-8")
try {
out.print(newLines.map(p => p._1 + ":" + p._2).mkString("\n"))
} finally {
out.close
}
}
override def getString(name: String): Option[String] = {
try {
Source.fromFile(filename).getLines().toList.flatMap(line => try {
val Array(id, value) = line.split(":")
if(id == name) Some(value) else None
} catch {
case (_: Exception) => None
}).headOption
} catch {
case (_: Exception) => None
}
}
override def putInt(name: String, value: Int): Unit = {
putString(name, value.toString)
}
override def getInt(name: String): Option[Int] = {
getString(name).flatMap(v => try {
Some(v.toInt)
} catch {
case (_: Exception) => None
})
}
override def putLong(name: String, value: Long): Unit = {
putString(name, value.toString)
}
override def getLong(name: String): Option[Long] = {
getString(name).flatMap(v => try {
Some(v.toLong)
} catch {
case (_: Exception) => None
})
}
override def putBoolean(name: String, value: Boolean): Unit = {
putString(name, value.toString)
}
override def getBoolean(name: String): Option[Boolean] = {
getString(name).flatMap(v => try {
Some(v.toBoolean)
} catch {
case (_: Exception) => None
})
}
}