码迷,mamicode.com
首页 > 其他好文 > 详细

scala当中的文件操作和网络请求

时间:2019-03-03 20:19:35      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:inpu   txt   imp   extend   buffere   文件写入   dso   puts   findall   

1、读取文件当中每一行的数据

def main(args: Array[String]): Unit = {

//注意文件的编码格式,如果编码格式不对,那么读取报错

val file: BufferedSource = Source.fromFile("F:\\files\\file.txt","GBK");

val lines: Iterator[String] = file.getLines()

for(line <- lines){

println(line)

}

//注意关闭文件

file.close()

}

如果要将文件内容转数组,直接调用toArray即可

? ?

2、读取词法单元和数字

如果想将以某个字符或某个正则表达式分开的字符成组读取,可以这么做:

def main(args: Array[String]): Unit = {

val file: BufferedSource = Source.fromFile("F:\\files\\file2.txt","GBK");

val split: Array[String] = file.mkString.split(" ")

println(split.mkString("\t"))

file.close()

}

? ?

3、读取网络资源、文件写入、控制台操作

1、读取网络资源

def main(args: Array[String]): Unit = {

val source: BufferedSource = Source.fromURL("http://www.baidu.com")

val string: String = source.mkString

? ?

println(string)

source.close()

}

2、文件写入操作

def main(args: Array[String]): Unit = {

val writer = new PrintWriter("F:files\\printWriter.txt")

for(i <- 1 to 100){

writer.println(i)

writer.flush()

}

writer.close()

}

?

3、控制台交互操作

def main(args: Array[String]): Unit = {

//控制台交互--API

print("请输入内容:")

val consoleLine1 = Console.readLine()

println("刚才输入的内容是:" + consoleLine1)

? ?

//控制台交互--API

print("请输入内容(API):")

val consoleLine2 = StdIn.readLine()

println("刚才输入的内容是:" + consoleLine2)

}

? ?

4、scala当中的序列化

@SerialVersionUID(1L)

class Person extends Serializable{

override def toString = name + "," + age

? ?

val name = "Nick"

val age = 20

? ?

}

? ?

object PersonMain extends App{

override def main(args: Array[String]): Unit = {

? ?

import java.io.{FileOutputStream, FileInputStream, ObjectOutputStream, ObjectInputStream}

val nick = new Person

val out = new ObjectOutputStream(new FileOutputStream("Nick.obj"))

out.writeObject(nick)

out.close()

? ?

val in = new ObjectInputStream(new FileInputStream("Nick.obj"))

val saveNick = in.readObject()

in.close()

println(saveNick)

}

}

? ?

5、scala当中的正则表达式

我们可以通过正则表达式匹配一个句子中所有符合匹配的内容,并输出:

? ?

def main(args: Array[String]): Unit = {

import scala.util.matching.Regex

val pattern1 = new Regex("(S|s)cala")

val pattern2 = "(S|s)cala".r

val str = "Scala is scalable and cool"

println((pattern2 findAllIn str).mkString(","))

}

?

scala当中的文件操作和网络请求

标签:inpu   txt   imp   extend   buffere   文件写入   dso   puts   findall   

原文地址:https://www.cnblogs.com/starzy/p/10466979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!