读取数据
Scala中Source单例对象提供从制定数据源中获取数据
scala.io.Source
按行读取
- 以行为单位,读取数据源中的数据,返回值是一个迭代器类型对象,接着通过toArray,toList方法获取数据
- Source.fromFile(“路径”, “编码表”)
val source = Source.fromFile("./data/1.txt")
val lines: Iterator[String] = source.getLines()
val list: List[String] = lines.toList
for(data <- list) println(data)
source.close()
按字符读取
通过hasNext() next() 方法灵活获取数据 ```scala val source = Source.fromFile(“./data/1.txt”) val iter:BufferedIterator[Char] = source.buffered while(iter.hasNext) { print(iter.next()) //不能用println否则一个字符占一行 } source.close()
//如果文件较少,可以读到字符串中 val source = Source.fromFile(“./data/1.txt”,”utf-8”) val str: String = source.mkString println(str)
<a name="NLBR6"></a>
### 读取词法单元和数字
```scala
/*
# 2.txt
10 23 32
22
44 55
*/
val source = Source.fromFile("./data/2.txt")
val str = source.mkString
// \s是空格
val strArray:Array[String] = str.split("\\s+")
//转换成Int数组
val intArray:Array[Int] = strArray.map(_.toInt)
//输出
for(i <- intArray) println(i)
source.close()
从URL或其它源读取
val source = Source.fromURL("http://www.itcast.cn")
val str1 = source.mkString
println(str)
读取二进制文件
val file = new File("./data/3.jpg")
val fis = new FileInputStream(file)
val bys = new Array[Byte](file.length().toInt)
val len = fis.read(bys)
println("读取到的长度为:" + len)
fis.close()
写入文件
往文件中写入指定数据
val fos = new FileOutputSteam("./data/4.txt")
fos.write("键盘敲烂", getBytes())
fos.write("月薪过万", getBytes())
fos.close()
序列化和反序列化
- 序列化:对象写到文件中
- 反序列化:文件加载到对象中
- 必须继承Serializable ```scala // class Person(var name: String, var age: Int) extends Serializable case class Person (var name: String, var age: Int)// 样例类会自动继承Serializable
def main(args: Array[String]): Unit = { // 序列化 val p = Person(“张三”,23) val oss = new ObjectOutputStream(new FileOutputStream(“./data/5.txt”)) //不存在会自动创建 oss.writeObject(p) oss.close()
// 反序列化 val ois = new ObjectInputStream(new FileInputStream(“./data/5.txt”)) val p: Person = ois.readObject().asInstaceOf[Person] println(p.name, p.age) ois.close() }
<a name="wElqH"></a>
### 案例:学生成绩表
```scala
object Test {
def main(args: Array[String]): Unit = {
val source = Source.fromFile("src/com/hqw/scala/studentgrade/data/student.txt")
val stuArray: Iterator[Array[String]] = source.getLines().map(_.split(" "))
val studentList = ListBuffer[Student]()
for(s <- stuArray) {
studentList += new Student(s(0), s(1).toInt, s(2).toInt, s(3).toInt)
}
val sortList = studentList.sortBy(_.getTotalScore()).reverse.toList
val bw = new BufferedWriter(new FileWriter("src/com/hqw/scala/studentgrade/data/stu.txt"))
for (s <- sortList) {
bw.write(s"${s.name} ${s.chinese} ${s.math} ${s.english} ${s.getTotalScore()}")
bw.newLine()
}
source.close()
bw.close()
}
}