读取数据

Scala中Source单例对象提供从制定数据源中获取数据
scala.io.Source

按行读取

  • 以行为单位,读取数据源中的数据,返回值是一个迭代器类型对象,接着通过toArray,toList方法获取数据
  • Source.fromFile(“路径”, “编码表”)
    1. val source = Source.fromFile("./data/1.txt")
    2. val lines: Iterator[String] = source.getLines()
    3. val list: List[String] = lines.toList
    4. for(data <- list) println(data)
    5. 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)

  1. <a name="NLBR6"></a>
  2. ### 读取词法单元和数字
  3. ```scala
  4. /*
  5. # 2.txt
  6. 10 23 32
  7. 22
  8. 44 55
  9. */
  10. val source = Source.fromFile("./data/2.txt")
  11. val str = source.mkString
  12. // \s是空格
  13. val strArray:Array[String] = str.split("\\s+")
  14. //转换成Int数组
  15. val intArray:Array[Int] = strArray.map(_.toInt)
  16. //输出
  17. for(i <- intArray) println(i)
  18. source.close()

从URL或其它源读取

  1. val source = Source.fromURL("http://www.itcast.cn")
  2. val str1 = source.mkString
  3. println(str)

读取二进制文件

  1. val file = new File("./data/3.jpg")
  2. val fis = new FileInputStream(file)
  3. val bys = new Array[Byte](file.length().toInt)
  4. val len = fis.read(bys)
  5. println("读取到的长度为:" + len)
  6. fis.close()

写入文件

scala中没有对写入的支持,使用Java类库

往文件中写入指定数据

  1. val fos = new FileOutputSteam("./data/4.txt")
  2. fos.write("键盘敲烂", getBytes())
  3. fos.write("月薪过万", getBytes())
  4. 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() }

  1. <a name="wElqH"></a>
  2. ### 案例:学生成绩表
  3. ```scala
  4. object Test {
  5. def main(args: Array[String]): Unit = {
  6. val source = Source.fromFile("src/com/hqw/scala/studentgrade/data/student.txt")
  7. val stuArray: Iterator[Array[String]] = source.getLines().map(_.split(" "))
  8. val studentList = ListBuffer[Student]()
  9. for(s <- stuArray) {
  10. studentList += new Student(s(0), s(1).toInt, s(2).toInt, s(3).toInt)
  11. }
  12. val sortList = studentList.sortBy(_.getTotalScore()).reverse.toList
  13. val bw = new BufferedWriter(new FileWriter("src/com/hqw/scala/studentgrade/data/stu.txt"))
  14. for (s <- sortList) {
  15. bw.write(s"${s.name} ${s.chinese} ${s.math} ${s.english} ${s.getTotalScore()}")
  16. bw.newLine()
  17. }
  18. source.close()
  19. bw.close()
  20. }
  21. }