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")).!

最新文章

  1. js基础总结
  2. js 、jsdoc生成33
  3. 好用的SQL TVP~~独家赠送[增-删-改-查]的例子
  4. 谁再说Matlab速度慢,我跟谁急
  5. Windows下设置自动关机命令
  6. AIM Tech Round 3 (Div. 2)
  7. 为VirtualBox里的Linux系统安装增强功能
  8. CodeForces 567C Geometric Progression
  9. JavaScript、jQuery、HTML5、Node.js实例大全-读书笔记2
  10. Oracle--常见Exception
  11. vsftpd安装指南
  12. S2第一本书内测
  13. [原创]K8Cscan插件之存活主机扫描
  14. linux系统中的文件权限详解(转)
  15. javascript面向对象精要第三章对象整理精要
  16. mysql服务里面没有启动项
  17. 面向对象编程其实很简单——Python 面向对象(初级篇)
  18. CentOS6.x安装RabbitMQ
  19. VC 与Matlab混合编程之引擎操作详解
  20. Asp.Ner Core定时任务

热门文章

  1. Matlab---length函数
  2. js 打开app应用,如果没有安装就去下载
  3. Stream的去重排序
  4. 如何获取Expression Design 4工具与Expression Blend 4工具
  5. 为什么打不开IDEA或webStorm官方网页?
  6. Python之路,Day3- Python基础(转载Alex)
  7. c++控制内存分配
  8. 洛谷P1352 没有上司的舞会 [2017年5月计划 清北学堂51精英班Day3]
  9. golang学习资料必备
  10. reverse 的用法