您的位置:首页 > 其它

Scala学习笔记6 (io)

2015-12-12 14:54 429 查看

http://blog.csdn.net/lyrebing/article/details/20369445


6.   io


6.1.     文件I/O


6.1.1.  读文件

scala特有的是scala.io.Source,例如:

import scala.io._

Source.fromFile("cn.scala","utf8").mkString

 

逐行读文件内容:

Source.fromFile(new java.io.File("cn.scala")).getLines().foreach(println)

 


6.1.2.  写文件

直接调用java的io:

import java.io._, java.nio.channels._, java.nio._

// 写文件

val f = new FileOutputStream("o.txt").getChannel

f write ByteBuffer.wrap("a little bit long ...".getBytes)

f close

 

或者:

var out = new java.io.FileWriter("./out.txt") // FileWriter("./out.txt", true) 为追加模式

out.write("hello\n")

out close

 


6.1.3.  复制文件

直接调用java的io:

val in  = new FileInputStream("in").getChannel

val out = new FileOutputStream("out").getChannel

in transferTo (0, in.size, out)

 


6.2.     网络I/O

import java.net.{URL, URLEncoder} import scala.io.Source.fromURL

fromURL(new URL("http://qh.appspot.com")).mkString


或者指定编码:
fromURL(new URL("http://qh.appspot.com"))(io.Codec.UTF8).mkString
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  scala