import java.io._, java.nio._
object IODemo{def main(args: Array[String]):Unit={val path ="D:\\data\\oo.txt"//read(path)//write(path)//copy
netIo
}// 读文件def read(path:String)={//scala特有的是scala.io.Sourceimport scala.io._
println(Source.fromFile(path,"utf8").mkString)//逐行读文件内容:
Source.fromFile(new java.io.File(path)).getLines().foreach(println)}// 写文件def write(path:String)={//直接调用java的ioval f =new FileOutputStream(path).getChannel
f write ByteBuffer.wrap("a little bit long ...".getBytes)
f close
// 或者// FileWriter("./out.txt", true) 为追加模式var out =new java.io.FileWriter(path)
out.write("hello\n")
out close
}// 拷贝文件内容def copy={val in_path ="D:\\data\\oo.txt"val out_path ="D:\\data\\oo_copy.txt"val in =new FileInputStream(in_path).getChannel
val out =new FileOutputStream(out_path).getChannel
in transferTo (0, in.size, out)}// 网络iodef netIo:Unit={import java.net.{URL, URLEncoder}import scala.io.Source.fromURL
println(fromURL(new URL("https://www.baidu.com")).mkString)//或者指定编码:
println(fromURL(new URL("https://www.baidu.com"))(io.Codec.UTF8).mkString)}}