遍历一个文件中的每一行
必须导入scala.io.Source类: import scala.io.Source
方法一: 使用Source.getLines返回的迭代器
val source = Source.fromFile("test.txt", "UTF-8") val lineIterator = source.getLines for (line <- lineIterator) println(line)
方法二: 将Source.getLines返回的迭代器,转换成数组
一个BufferedSource对象的getLines方法,只能调用一次,一次调用完之后,遍历了迭代器里所有的内容,就已经把文件里的内容读取完了
如果反复调用source.getLines,是获取不到内容的
此时,必须重新创建一个BufferedSource对象
val source = Source.fromFile("test.txt", "UTF-8") val lines = source.getLines.toArray for(line <- lines) println(line)
方法三: 调用Source.mkString,返回文本中所有的内容
val source = Source.fromFile("test.txt", "UTF-8") val lines = source.mkString
使用完BufferedSource对象之后,调用BufferedSource.close方法,关闭IO流资源
遍历一个文件中的每一个字符
BufferedSource,也实现了一个Iterator[Char]的这么一个trait
val source = Source.fromFile("test.txt", "UTF-8") for(c <- source) print(c)
从URL以及字符串中读取字符
val source = Source.fromURL("http://www.baidu.com", "UTF-8") val source = Source.fromString("Hello World")
结合Java IO流,读取任意文件
import java.io._ val fis = new FileInputStream(new File("test.txt")) val fos = new FileOutputStream(new File("test1.txt")) val buf = new Array[Byte](1024) fis.read(buf) fos.write(buf, 0, 1024) fis.close() fos.close()
结合Java IO流,写文件
val pw = new PrintWriter("test2.txt") pw.println("Hello World") pw.close()
递归遍历子目录
def getSubdirIterator(dir: File): Iterator[File] = { val childDirs = dir.listFiles.filter(_.isDirectory) childDirs.toIterator ++ childDirs.toIterator.flatMap(getSubdirIterator _) } val iterator = getSubdirIterator(new File("Desktop")) for(d <- iterator) println(d)
序列化以及反序列化(Java序列化和反序列化机制)
如果要序列化,那么就必须让类,有一个@SerialVersionUID,定义一个版本号 要让类继承一个Serializable trait
@SerialVersionUID(42L) class Person(val name: String) extends Serializable
val leo = new Person("leo") import java.io._ val oos = new ObjectOutputStream(new FileOutputStream("test.obj")) oos.writeObject(leo) oos.close() val ois = new ObjectInputStream(new FileInputStream("test.obj")) val restoredLeo = ois.readObject().asInstanceOf[Person] restoredLeo.name