标签:inpu txt imp extend buffere 文件写入 dso puts findall
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即可
? ?
如果想将以某个字符或某个正则表达式分开的字符成组读取,可以这么做:
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() } |
? ?
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) } |
? ?
@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) } } |
? ?
我们可以通过正则表达式匹配一个句子中所有符合匹配的内容,并输出:
? ?
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(",")) } |
?
标签:inpu txt imp extend buffere 文件写入 dso puts findall
原文地址:https://www.cnblogs.com/starzy/p/10466979.html