scala当中的文件操作和网络请求的实现方法
人气:01、读取文件当中每一行的数据
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(",")) }
您可能感兴趣的文章:
加载全部内容