Scala中文件的读取、写入、控制台输入操作代码实战

来源:互联网 发布:php高级工程师 面试题 编辑:程序博客网 时间:2024/04/29 16:56

内容:

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.toDoubleval 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)








0 0
原创粉丝点击