scala2.11读取文件

1.读取行

要读取文件的所有行,可以调用scala.io.Source对象的getLines方法:

import scala.io.Source
val source = Source.fromFile("myfile.txt", "UTF-8")
val lineIterator = source.getLines
val lines1 =lineIterator.toArray  
val lines2 = lineIterator.toBuffer
//将文件内容读成字符串
val lines = source.mkString
source.close 

2.读取字符

val iter = source.buffered  
  
while(iter.hasNext){  
  if(iter.next == '王'){  
    println("wang")  
  }else{  
    println("-")  
  }  
}  

3.读取词法单元或数字

val iter 2= source.mkString.split("\\s+")  
  
val num = for(w <- iter2) yield w.toDouble  
  
for(i <- num) println(i) 

4.从URL或其它资源读取

val source1 = Source.fromURL("http://baidu.com")//URL读取  
val source2 = Source.fromString("hello")//读取给定的字符串-多用于调试 
import scala.io.StdIn
val ms=StdIn.readLine()  

5.读取二进制文件

import java.io.{File, FileInputStream}
val file = new File(" ")
val in = new FileInputStream(file)
val bytes = new Array[Byte](file.length.toInt)
in.read(bytes)
in.close() 

6.写入文本

val out = new PrintWriter("numbers.txt")
for (i <- 1 to 100) {
out.println(i)
out.print(f"$quantity%6d $price%10.2f")
}
out.close() 

7.访问目录

import java.nio.file._
val dirname = "/home/cay/scala-impatient/code"
val entries = Files.walk(Paths.get(dirname)) // or Files.list
try {
entries.forEach(p => println(p))
} finally {
entries.close()
} 

8.序列化

@SerialVersionUID(42L) class Person extends Serializable{}
class Person extends Serializable {
private val friends = new ArrayBuffer[Person] // OK—ArrayBuffer is serializable
}
val fred = new Person(...)
import java.io._
val out = new ObjectOutputStream(new FileOutputStream("/tmp/test.obj"))
out.writeObject(fred)
out.close()
val in = new ObjectInputStream(new FileInputStream("/tmp/test.obj"))
val savedFred = in.readObject().asInstanceOf[Person]

9.scala脚本与shell命令

import scala.sys.process._
"ls -al ..".!
("ls -al /" #| "grep u").!
#输出重定向到文件
("ls -al /" #> new File("filelist.txt")).!
#追加到末尾
("ls -al /etc" #>> new File("filelist.txt")).!
#把某个文件的内容作为输入
("grep u" #< new File("filelist.txt")).!
#从URL重定向输入
("grep Scala" #< new URL("http://horstmann.com/index.html")).!
posted @ 2018-05-16 17:22  飞末  阅读(7725)  评论(0编辑  收藏  举报