Scala io操作

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)

2. 写文件

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

3. 复制文件

val in = new FileInputStream(“in”).getChannel 

val out = new FileOutputStream(“out”).getChannel 

in.transferTo (0, in.size, out)

4. 网络I/O

‘ 

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

fromURL(new URL(“http://www.baidu.com“)).mkString

或者指定编码: 

fromURL(new URL(“http://www.baidu.com“))(io.Codec.UTF8).mkString

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值