这篇文章主要介绍了Scala中如何实现文件读取、写入、控制台操作,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
创新互联公司是一家专业提供友谊企业网站建设,专注与网站建设、成都做网站、H5场景定制、小程序制作等业务。10年已为友谊众多企业、政府机构等服务。创新互联专业网络公司优惠进行中。
Scala文件读取
E盘根目录下scalaIO.txt文件内容如下:
文件读取示例代码:
//文件读取 val file=Source.fromFile("E:\\scalaIO.txt") for(line <- file.getLines) { println(line) } file.close
说明1:file=Source.fromFile(“E:\scalaIO.txt”),其中Source中的fromFile()方法源自 import scala.io.Source源码包,源码如下图:
file.getLines(),返回的是一个迭代器-Iterator;源码如下:(scala.io)
Scala 网络资源读取
//网络资源读取 val webFile=Source.fromURL("http://spark.apache.org") webFile.foreach(print) webFile.close()
fromURL()方法源码如下:
/** same as fromURL(new URL(s)) */ def fromURL(s: String)(implicit codec: Codec): BufferedSource = fromURL(new URL(s))(codec)
读取的网络资源资源内容如下:
Apache Spark™ - Lightning-Fast Cluster Computing
Archive
Built-in Libraries:
Run programs up to 100x faster than
Hadoop MapReduce in memory, or 10x faster on disk.
Spark has an advanced DAG execution engine that supports cyclic data flow and
in-memory computing.
Write applications quickly in Java, Scala, Python, R.
Spark offers over 80 high-level operators that make it easy to build parallel apps.
And you can use it interactively
from the Scala, Python and R shells.
Combine SQL, streaming, and complex analytics.
Spark powers a stack of libraries including
SQL and DataFrames, MLlib for machine learning,
GraphX, and Spark Streaming.
You can combine these libraries seamlessly in the same application.
Speed
Ease of Use
text_file.flatMap(lambda line: line.split())
.map(lambda word: (word, 1))
.reduceByKey(lambda a, b: a+b)
Generality