1. IO
import java.io._, java.nio._
object IODemo{
def main(args: Array[String]): Unit = {
val path = "D:\\data\\oo.txt"
netIo
}
def read(path:String)= {
import scala.io._
println(Source.fromFile(path, "utf8").mkString)
Source.fromFile(new java.io.File(path)).getLines().foreach(println)
}
def write(path:String)={
val f = new FileOutputStream(path).getChannel
f write ByteBuffer.wrap("a little bit long ...".getBytes)
f close
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)
}
def 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)
}
}
2. XML
2.1 生成XML
def set(): Unit = {
val (name, age) = ("小明", 12)
val xml1 = <xml><name>{name}</name><age>{age}</age><address>{"北京"}</address></xml> toString;
println(xml1)
val xml2 = <xml>{(1 to 3).map(i => <index>{i}</index>)}</xml>
println(xml2)
}
2.2 读取XML
def get(): Unit = {
val xml1 = <r><index>1</index> <index>2</index> <index>3</index></r>
val list = (xml1 \ "index").map(_.text.toInt)
println(list)
val xml2 = <users><user name="xiaom"/></users>
val <users>{u}</users> = xml2
println(u)
val xml_5 = <users><user name="xioam"><age>20</age></user> <user name="xiaoh"><age>30</age></user></users>
(xml_5 \ "user").map(println(_))
(xml_5 \ "user" \ "age").map(println(_))
(xml_5 \\ "age").map(println(_))
(xml_5 \ "_").map(println(_))
}
2.3 访问属性
def getValues(): Unit ={
val xml1 = <users><u name="xiaom"/><u name="xiaoh"/><u name="xiaog"/></users>
(xml1 \ "u" \\ "@name")foreach println
val xml2 =
<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>
val res = for (item <- xml2 \ "item";
price = (item \ "@price").text.toDouble;
quantity = (item \ "@quantity").text.toInt) yield (price * quantity)
println(res)
printf("$%.2f\n", res.sum)
}
2.4 格式化输出
def xmlFormat(): Unit ={
val xml1 = <users><u name="xiaom"/><u name="xiaoh"/><u name="xiaog"/></users>
val formatter = new xml.PrettyPrinter(80, 4)
println(formatter formatNodes xml1)
}
2.5 模式匹配
def xmlMatch(): Unit ={
println(proc(<a>apple</a>))
println(proc(<b>banana</b>))
println(proc(<c>cherry</c>))
}
def proc(node: scala.xml.Node): String =
node match {
case <a>{contents}</a> => "It's an a: " + contents
case <b>{contents}</b> => "It's a b: " + contents
case _ => "It's something else."
}