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