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)读取的网络资源资源内容如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Apache Spark™ - Lightning-Fast Cluster Computing </title> <meta name="description" content="Apache Spark is a fast and general engine for big data processing, with built-in modules for streaming, SQL, machine learning and graph processing."> <!-- Bootstrap core CSS --> <link href="/css/cerulean.min.css" rel="external nofollow" rel="stylesheet"> <link href="/css/custom.css" rel="external nofollow" rel="stylesheet"> <script type="text/javascript"> <!-- Google Analytics initialization --> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-32518208-2']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http:///") webFile.foreach(print) webFile.close()读取中文资源站点,出现编码混乱问题如下:(解决办法自行解决,本文不是重点)
Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。