import scala.io.Source
//文件遍历
object Score extends App {
//读文件
val source = Source.fromFile("c://test.txt","UTF-8") //BufferedSource对象
val lines = source.getLines() //Iterator[String]
lines.toArray //转为数组
source.mkString //转为String
//遍历每一行
for (line <- lines.toArray){
println(line)
}
//遍历字符
for (c <- source){
println(c)
}
//URL以及字符串读字符
val source1 = Source.fromURL("www.baidu.com", "UTF-8")
val source2 = Source.fromString("www.baidu.com")
//拷贝文件
import java.io._
val file = new File("C:\\test.txt") //java.io.File
val fis = new FileInputStream(file)
val fos = new FileOutputStream(new File("C:\\test1.txt"))
val buf = new Array[Byte](1024)
fis.read(buf)
fos.write(buf)
fis.close()
fos.close()
//返回当前目录下所有子目录及递归子目录
def getSubdirIterator(dir: File): Iterator[File] = {
val childDirs = dir.listFiles.filter(_.isDirectory)
childDirs.toIterator ++ childDirs.toIterator.flatMap(getSubdirIterator _)
}
val it = getSubdirIterator(new File("C://"))
for(d <- it){
println(d)
}
//scala序列化、反序列化使用的是java的
@SerialVersionUID(1L) class Person(val name: String) extends Serializable
val cys = new Person("cys")
val oos = new ObjectOutputStream((new FileOutputStream(new File("C://text.txt"))))
oos.writeObject(cys)
oos.close()
val ois = new ObjectInputStream(new FileInputStream(new File("C://text.txt")))
val cys1 = ois.readObject().asInstanceOf[Person]
ois.close()
}
09-16