Read configuration and variables

1 read the properties file

The methods are different, and the file paths and file types that can be read are also different.

Several ways to read .properties configuration files in Java

-

1.1 Scala language reading

1) Read the properties file under any path

import java.io.{BufferedReader, FileReader}
import java.util.Properties


/**
 * 读取任意路径下的properties文件
 * */
object ConfManager {

    private val prop: Properties = new Properties

    /**
     * 读取配置文件
     */
    def readConf(file_path: String): Unit = {
        try {
            val in = new BufferedReader(new FileReader(file_path))
            prop.load(in)
            in.close()
        } catch {
            case e: Exception => {
                System.err.println("读取配置文件失败!")
                System.exit(1)
            }
        }
    }

    def getString(key: String): String = {
        val value = prop.getProperty(key)
        if (null == value) {
            System.err.println(s"${key} 没有赋值")
            System.exit(1)
        }
        value
    }

    def getInt(key: String): Int = {
        getString(key).toInt
    }
    
}

2) Can only read resources under the resource directory

import java.io.{BufferedReader, FileReader}
import java.util.Properties


/**
 * 读取任意路径下的properties文件
 * */
object ConfManager {

    private val prop: Properties = new Properties

    /**
     * 读取配置文件
     */
    def readConf(file_path: String): Unit = {
        try {
            val in = Thread.currentThread().getContextClassLoader.getResourceAsStream( "config.properties" )
            prop.load( in )
            in.close()
        } catch {
            case e: Exception => {
                System.err.println("读取配置文件失败!")
                System.exit(1)
            }
        }
    }

    def getString(key: String): String = {
        val value = prop.getProperty(key)
        if (null == value) {
            System.err.println(s"${key} 没有赋值")
            System.exit(1)
        }
        value
    }

    def getInt(key: String): Int = {
        getString(key).toInt
    }
    
}

2 Get environment variables

# shell
if [[ ${AWS_DEFAULT_REGION} = eu-west-1 ]]
then
   region_flag="ireland"
elif [[ ${AWS_DEFAULT_REGION} = ap-south-1 ]]
then
   region_flag="india"
else
    echo "error:获取了错误的区域标记"
    exit 1
fi

# scala
val region = sys.env("AWS_DEFAULT_REGION")


Guess you like

Origin blog.csdn.net/weixin_40829577/article/details/123238364
Recommended