Scala 进行文件写操作,直接用的都是 java中 的 I/O 类 (java.io.File):
1.读取本地磁盘
var source = Source.fromFile("D:\\test.txt","GB2312")
var lines = source.getLines; //获得迭代器
for(line <- lines) println(line)
var sourceArr = source.getLines().toArray //读取成一个数组
var sourceBuffer = source.getLines().toBuffer //读取成一个缓冲
val str = source.mkString; //小文件读取成一个字符串
for(c <- source){println(c)} //逐个字符读取
source.getLines().foreach { line => println(line) } //scala的写法
source.close() //用完之后需要进行关闭操作
2.从字符串读取
val sourceFromString = Source.fromString("hello this is scala note")
println(sourceFromString.mkString("<","-",">"))
sourceFromString.close()
3.从URL读取,并写入本地磁盘
val sourceFromUrl = Source.fromURL("http://www.baidu.com","utf-8")
val urlLines = sourceFromUrl.getLines();
var print = new PrintWriter("d:\\baidu.html");
for(line <- urlLines){
print.println(line)
print.flush()
}
print.close()
sourceFromUrl.close()
4.读取控制台的输入
println("how old are you")
var age = scala.io.StdIn.readInt()
var readLine = scala.io.StdIn.readLine()
println("your age is "+age)
5.读取二进制文件:scala不能直接读取和写入二进制文件,需要借助于JAVA来进行读取,这种方式还是按照java方式来去写scala,后期scala熟练后再进行更改
def readAndWriteBinaryFile: Unit = {
var file = new File("D:\\mycat.wmv")
val bis = new BufferedInputStream(new FileInputStream(file))
var byte = new Array[Byte](4096)
var len = 0
var outFile = new File("d:\\mycat_copy.wmv")
var bos = new BufferedOutputStream(new FileOutputStream(outFile))
while ({ len = bis.read(byte); len != -1 }) { //一定要这么写
/*
* while((len = bis.read(byte)) != -1){
* 这么写会出现comparing values of types Unit and Int using `!='
* will always yield true ,并在len = -1出现异常
*/
bos.write(byte, 0, len);
bos.flush();
}
bos.close()
bis.close()
}