内容:
1、文件的读取、写入操作
2、控制台操作代码实战
val file = Source.fromFile("E:\\WangJialin.txt")
for(line <-file.getLines){println(file)
file.close
}
1、读取E:\\Wangjialin.txt文本文件
其中Source.fromFile是一个BufferedSource类(根据具体的访问文件放回了一个迭代器,迭代器中为文件的内容),fromFile得到迭代器后,file.getLines按行打印出文件内容,最后关闭!
val file1 = Source.fromURL("http://spark.apache.org/")
file1.foreach {println _}
file1.close()<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"> </span>
//每次打印一行:foreach(println(_))
2、读取网页文件源码信息 http://spark.apache.org/
其中Source.fromURL 获得地址同存于BufferedSource迭代器中,再通过foreach进行循环迭代打印
3、读取词组单元和数字
val tokens = source.mkString.sqlit("\\s+") // 根据正则读取词法单元
// 转换成数字
val numbers = for (w <- tokens) yield w.toDouble
val numbers = tokens.map(_.toDouble)
4、从非文件源读取// 从URL读取,需要注意字符编码
val source1 = Source.fromURL("http://horstmann.com", "UTF-8")
val source2 = Source.fromString("Hello, world!") // 从指定的字符串读取,调试时很有用
val source3 = Source.stdin // 从标准输入读取
5、写入文件 val write = new PrintWriter(new File("Hello.txt"))
for(i<- 1 to 100) write.println(i)
write.close()
6、控制台输入 val file2 = Console.readLine()
println("thinks"+ file2)
版权声明:本文为kxr0502原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。