在Scala編程中,常常會用到調用第三方接口,獲取返回值(文件內容是字符類型,或者返回的是字符串),那麼使用Scala自帶的Scala.io.Source類,將非常方便。
舉例如下:
1、url="http://localhost:9008/services/user/getSampleValue"
2、返回值:有兩種
(1)字符串:"{"status":"1","timestamp":"201612131742","sampleList":[{"domain":"www.linuxidc.com","proportion":"0.8"},{"domain":"www.linuxidc.net","proportion":"0.4"}]}"
(2)文件流(內容是字符):sample.txt文件
內容是:"{"status":"1","timestamp":"201612131742","sampleList":[{"domain":"www.linuxidc.com","proportion":"0.8"},{"domain":"www.linuxidc.net","proportion":"0.4"}]}"
實現的代碼如下:
import java.io.PrintWriter
import scala.io.Source
/**
* Created by yangjf on 2016/12/14
* Update date:
* Time: 9:35
* Describle :測試使用Scala調用url
* Result of Test:通過
* Command:
*/
object TestScalaUrl {
def main(args: Array[String]) {
//獲取抽樣參數的url
val url="http://localhost:9008/services/user/getSampleValue"
//鏈接url,獲取返回值
val fileContent = Source.fromURL(url,"utf-8").mkString
//寫入本地磁盤
val pw = new PrintWriter("F:/test.ip")
pw.write(fileContent)
pw.flush
pw.close
}
//可以從InputStream中讀取
def inputToString(is: java.io.InputStream): String = {
val lines: Iterator[String] = scala.io.Source.fromInputStream(is, "utf-8").getLines()
val sb = new StringBuilder()
lines.foreach(sb.append(_))
sb.toString()
}
//將輸入流寫入文件(test.txt)中
//參數f---> val file = new File("F:/test.txt")
def inputToFile(is: java.io.InputStream, f: java.io.File) {
val in: BufferedSource = scala.io.Source.fromInputStream(is)
val out = new java.io.PrintWriter(f)
try {
in.getLines().foreach(out.print(_))//等價write,只是多了一句if(s==null)s="null"
}
finally {
out.close
}
}
}
參考Scala 的API:
http://www.scala-lang.org/api/current/scala/io/Source.html