Scala学习笔记--文件IO
2015-03-08 22:15
344 查看
补充:
http://blog.csdn.net/lyrebing/article/details/20369445 http://developer.51cto.com/art/200907/134957.htm http://nerd-is.in/2013-08/scala-learning-files-and-regular-expressions/
读取行
读取字符(一个一个字符处理)
读取词法单元和数字
从URL或其他源读取
运行结果为网址的html
读取二进制文件
Scala没有提供读取二进制文件的方法,需要使用Java类库
写入文本文件
http://blog.csdn.net/lyrebing/article/details/20369445 http://developer.51cto.com/art/200907/134957.htm http://nerd-is.in/2013-08/scala-learning-files-and-regular-expressions/
读取行
//读取文件中的所有行,可以调用scala.io.Source对象的getLines方法 object LineIO{ def main(args:Array[String]):Unit = { val source = Source.fromFile("F:\\way.txt","UTF-8") //第一个参数可以是字符串或者是java.io.File //第二个参数可省略 val lineIterator =source.getLines //结果是一个迭代器 for(l<-lineIterator) println(l) //或者可以对迭代器应用toArray或toBuffer方法,将行放到数组或数组缓冲当中 val lines = source.getLines.toArray //将整个文件读取成一个字符串 //val contents = source.mkString; source.close } }
读取字符(一个一个字符处理)
//按字符处理 object CharIO{ def main(args:Array[String]):Unit={ val source =Source.fromFile("F:\\way.txt","UTF-8") val iter= source.buffered //println(iter.length) while(iter.hasNext){ print(iter.next.toString) } source.close } }
读取词法单元和数字
object NumIO{ def main(args:Array[String]):Unit={ val source = Source.fromFile("F:\\num.txt","UTF-8") val tockens = source.mkString.split(" ") for(w<-tockens){ println(w.toInt) } //另一种方法 val numbers = for(w<-tockens) yield w.toDouble for(num<-numbers){ println(num) } //另一种方法 val numbers2 = tockens.map(_.toDouble) } }
从URL或其他源读取
//读取非文件源的方法 object URLIO{ def main(args:Array[String]):Unit={ //从URL读取 val source= Source.fromURL("http://www.baidu.com","UTF-8") val lineIterator =source.getLines for(l<-lineIterator){ println(l.toString()) } //从给定的字符串读取--调试有用 val source2= Source.fromString("Hello world") //从标准输入读取 val source3 = Source.stdin } }
运行结果为网址的html
读取二进制文件
Scala没有提供读取二进制文件的方法,需要使用Java类库
object URLIO{ def main(args:Array[String]):Unit={ val file = new File("F:\\info.bin") val in = new FileInputStream(file) val bytes = new Array[Byte](file.length.toInt) in.read(bytes) in.close } }
写入文本文件
object WriteIO{ def main(args:Array[String]):Unit={ val out = new PrintWriter("F:\\numbers.txt") for(i<-1 to 100) out.println(i) out.close } }
相关文章推荐
- scala学习笔记之文件IO操作
- [零散篇]Java学习笔记---Java的对象序列化以及文件IO处理
- Java IO 实现文件复制 -Java 学习笔记 (25)
- java io文件学习笔记
- Scala2.11.7学习笔记(九)文件操作
- linux基础学习笔记-8-文件IO
- Scala学习笔记15【Scala文件操作】
- scala 学习笔记(02) 元组Tuple、数组Array、Map、文件读写、网页抓取示例
- Unix学习笔记------文件IO------使用lseek设置文件当前读写偏移量(即:当前的读写位置)
- Scala学习笔记(四):从文件里读取文本行
- python学习笔记 IO 文件读写
- Java学习笔记——File类文件管理及IO读写、复制操作
- 树莓派学习笔记——使用文件IO操作GPIO SysFs方式
- Java文件IO学习笔记(二)---文件锁定
- C++标准库 之 iostream库的学习笔记(四) fstream类的使用和总结文件IO
- Java学习笔记——File类文件管理及IO读写、复制操作
- java基础-用IO演示文件的复制过程(学习笔记)
- [学习笔记]Java IO之文件
- [学习笔记]Java IO之文件
- [学习笔记]Java文件IO操作------实现对文件的读取与写入