1. 程式人生 > >Scala學習筆記(8)—— Scala操作外部資料

Scala學習筆記(8)—— Scala操作外部資料

1 Scala 讀取檔案

package com.scalatest.scala.class09

import java.net.URL

import scala.io.Source

object FileApp {
    def main(args: Array[String]): Unit = {
        val file = Source.fromFile("d:/test.txt")

        def readLine() = {
            for (line <- file.getLines()) {
                println(
line) } } //readLine() def readChar() = { for (ele <- file) { println(ele) } } // readChar() def readNet() = { val file = Source.fromURL("http://www.baidu.com") for (line <-
file.getLines()) { println(line) } } readNet() } }

2 Scala 操作 MySQL 資料庫

  • POM 新增依賴
<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version
>
5.1.38</version> </dependency>
package com.scalatest.scala.class09

import java.sql.{Connection, DriverManager, Statement}

object MySQLApp {
    def main(args: Array[String]): Unit = {
        val url = "jdbc:mysql://localhost:3306/mysql"
        val username = "root"
        val password = "root"

        var connection: Connection = null
        var statement: Statement = null

        try {

            classOf[com.mysql.jdbc.Driver]
            connection = DriverManager.getConnection(url, username, password)

            statement = connection.createStatement()

            val resultSet = statement.executeQuery("select host,user from user")

            while (resultSet.next()) {
                val host = resultSet.getString("host")
                val user = resultSet.getString("user")

                println(s"$host,$user")
            }
        } catch {
            case e: Exception => e.printStackTrace()
        } finally {
            if (connection == null) {
                connection.close()
            }
        }


    }
}

在這裡插入圖片描述

3 Scala 讀取 XML 檔案

在這裡插入圖片描述

<symbols>
    <symbol ticker="AAPL">
        <units>200</units>
    </symbol>

    <units>300</units>

    <symbol ticker="AAPL">
        <units>400</units>
    </symbol>

</symbols>

3.1 讀取 XML 內容

package com.scalatest.scala.class09

import java.io.{FileInputStream, InputStreamReader}

import scala.xml.XML

object XMLApp {
    def main(args: Array[String]): Unit = {
        loadXML()
    }

    def loadXML(): Unit = {
        //        val xml = XML.load(this.getClass.getClassLoader.getResource("test.xml"))
        //        println(xml)

        //        val xml = XML.load(new FileInputStream("D:\\Data\\JavaProject\\scalatest\\src\\main\\resources\\test.xml"))
        //        println(xml)

        val xml = XML.load(new InputStreamReader(
            new FileInputStream("D:\\Data\\JavaProject\\scalatest\\src\\main\\resources\\test.xml")
        ))
        println(xml)
    }
}

3.2 讀取標籤內容