spark讀取外部配置文件的方法
spark-submit --files /tmp/fileName /tmp/test.jar
使用spark提交時使用--files參數,spark會將將本地的文件上傳的hdfs,然后分發給每個executor
在程序中只需要使用文件名獲取數據
val filePath ="fileName"
val props =newProperties()
props.load(newFileInputStream(filePath))
//發送到executor去執行
val rdd=sc.parallelize(0to3)
rdd.foreach(index=>
props.keySet().toArray().foreach(x=>println(x+"\t"+props.getProperty(x.toString)))
)
java的方式也是一樣的,在這就不寫了
3、--files ./config.properties
讀一般文件:
val t: BufferedSource = scala.io.Source.fromFile("config.properties")
t.getLines().foreach(t=>println(t))
讀配置文件:
/* val config = "config.properties"
val prop = new Properties()
prop.load(new FileInputStream(config))
val keyset = prop.keySet().toArray()
keyset.foreach(t=>println(t+" "+prop.getProperty(t.toString)))*/
| 配置文件類加載測試 | 配置采用 key=value 的形式 | client/cluster | 采用 sc.getConf.get 方法;配合submit 參數–properties-file 上傳配置文件; 配置文件key value 以空格為分隔符 |
| 配置文件類加載測試 | 配置采用 key=value 的形式 | client/cluster | 采用java.util.Properties 方法;配置文件打包到jar包里; 配置文件key value 以“=”為分隔符 |
| 資源文件類加載測試 | 普通文本格式,非key value模式 | client/cluster | 采用scala.io.Source.fromFile 方法;資源文件采用submit 參數–files 上傳; |
| 資源文件類加載測試 | 普通文本格式,非key value模式 | client/cluster | 采用scala.io.Source.fromFile和getResourceAsStream方法;資源文件打包到jar包中; |
在/tmp下創建a文件,內容為:
this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data this is a test data
spark-shell --master yarn --files "/tmp/a"
可以看到a文件被上傳到hdfs上了:

在代碼中讀取該文件,如下

可以看見這個文件在excutor被正確讀取:且在兩個excutor上分別執行,一個打印了22行,一個打印11行,原文件總共11行;上述rdd公有三個元素,每個元素遍歷時打印一遍,總共
3*11=33


