遍歷一個文件中的每一行
必須導入scala.io.Source類: import scala.io.Source
方法一: 使用Source.getLines返回的迭代器
val source = Source.fromFile("C://Users//Administrator//Desktop//test.txt", "UTF-8")
val lineIterator = source.getLines
for (line <- lineIterator) println(line)
方法二: 將Source.getLines返回的迭代器,轉換成數組
這里說明一點: 一個BufferedSource對象的getLines方法,只能調用一次,一次調用完之后,遍歷了迭代器里所有的內容,就已經把文件里的內容讀取完了
如果反復調用source.getLines,是獲取不到內容的
此時,必須重新創建一個BufferedSource對象
val source = Source.fromFile("C://Users//Administrator//Desktop//test.txt", "UTF-8")
val lines = source.getLines.toArray
for(line <- lines) println(line)
方法三: 調用Source.mkString,返回文本中所有的內容
val source = Source.fromFile("C://Users//Administrator//Desktop//test.txt", "UTF-8")
val lines = source.mkString
使用完BufferedSource對象之后,調用BufferedSource.close方法,關閉IO流資源
遍歷一個文件中的每一個字符
BufferedSource,也實現了一個Iterator[Char]的這么一個trait
val source = Source.fromFile("C://Users//Administrator//Desktop//test.txt", "UTF-8")
for(c <- source) print(c)
從URL以及字符串中讀取字符
val source = Source.fromURL("http://www.baidu.com", "UTF-8")
val source = Source.fromString("Hello World")
結合Java IO流,讀取任意文件
千萬不要以為,spark就是會scala就可以了
也千萬不要以為,scala,就是跟java一點關系都沒有,甚至于完全可以替代java
spark的源碼實際上是由scala和java共同編寫而成的,Java的多線程
scala,本身的編程語言的功能,就不是特別的強大和完善,比如說,scala甚至不能很方便地寫文件,必須依賴于java的io流才可以
所以說,scala,其實主要就是針對某些特定領域的一些復雜系統的,比較適用的一種編程語言而已
完全無法替代java的,scala和java是相輔相成,榮辱與共的這么一種,共生關系
scala還有一種作用,可以用scala,編寫spark的作業
案例: 結合java IO流,做一個文件拷貝的案例
import java.io._
val fis = new FileInputStream(new File("C://Users//Administrator//Desktop//test.txt"))
val fos = new FileOutputStream(new File("C://Users//Administrator//Desktop//test3.txt"))
val buf = new Array[Byte](1024)
fis.read(buf)
fos.write(buf, 0, 1024)
fis.close()
fos.close()
結合Java IO流,寫文件
val pw = new PrintWriter("C://Users//Administrator//Desktop//test4.txt")
pw.println("Hello World")
pw.close()
遞歸遍歷子目錄
def getSubdirIterator(dir: File): Iterator[File] = {
val childDirs = dir.listFiles.filter(_.isDirectory)
childDirs.toIterator ++ childDirs.toIterator.flatMap(getSubdirIterator _)
}
val iterator = getSubdirIterator(new File("C://Users//Administrator//Desktop"))
for(d <- iterator) println(d)
序列化以及反序列化(Java序列化和反序列化機制)
如果要序列化,那么就必須讓類,有一個@SerialVersionUID,定義一個版本號
要讓類繼承一個Serializable trait
@SerialVersionUID(42L) class Person(val name: String) extends Serializable
val leo = new Person("leo")
import java.io._
val oos = new ObjectOutputStream(new FileOutputStream("C://Users//Administrator//Desktop//test.obj"))
oos.writeObject(leo)
oos.close()
val ois = new ObjectInputStream(new FileInputStream("C://Users//Administrator//Desktop//test.obj"))
val restoredLeo = ois.readObject().asInstanceOf[Person]
restoredLeo.name