配置练习代码:
package com.dtinone.hadooptest1.hsfsapi;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
public class Conf {
public static void main(String[] args) throws Exception {
/**
* 底层会加载一堆的配置文件:
*
* core-default.xml
* hdfs-default.xml
* mapred-default.xml
* yarn-default.xml
*/
Configuration conf = new Configuration();
conf.addResource("192.168.180.88\\opt\\apps\\hadoop-2.7.3\\etc\\hadoop\\hdfs-site.xml");
/**
* 当前这个hdfs-site.xml文件就放置在这个项目中的src下。也就是classpath路径下。
* 所以 FS在初始化的时候,会把hdfs-site.xml这个文件中的name-value对解析到conf中
*
*
* 但是:
*
* 1、如果hdfs-site.xml 不在src下, 看是否能加载??? 不能
*
* 2、如果文件名不叫做 hdfs-default.xml 或者 hdsf-site.xml 看是否能自动加载??? 不能
*
* 得出的结论:
*
* 如果需要项目代码自动加载配置文件中的信息,那么就必须把配置文件改成-default.xml或者-site.xml的名称
* 而且必须放置在src下
*
* 那如果不叫这个名,或者不在src下,也需要加载这些配置文件中的参数:
*
* 必须使用conf对象提供的一些方法去手动加载
*/
// conf.addResource("hdfs-site.xml");
conf.set("dfs.replication", "1");
/**
* 依次加载的参数信息的顺序是:
*
* 1、加载 core/hdfs/mapred/yarn-default.xml
*
* 2、加载通过conf.addResources()加载的配置文件
*
* 3、加载conf.set(name, value)
*/
FileSystem fs = FileSystem.get(conf);
System.out.println(conf.get("dfs.replication"));
Iterator<Entry<String, String>> iterator = conf.iterator();
while (iterator.hasNext()) {
Entry<String, String> e = iterator.next();
System.out.println(e.getKey() + "\t" + e.getValue());
}
}
}
代码解释:1、增加配置项
conf.addResource("192.168.180.88\\opt\\apps\\hadoop-2.7.3\\etc\\hadoop\\hdfs-site.xml");
192.168.180.88\opt\apps\hadoop-2.7.3\etc\hadoop\是我虚拟机的配置文件的路径
2、更改或者设置配置内容
conf.set("dfs.replication", "1");
3、获取配置值
conf.get("dfs.replication");
4、通过迭代器获取所有默认配置信息,包括已设置的配置信息
Iterator<Entry<String, String>> iterator = conf.iterator();
while (iterator.hasNext()) {
Entry<String, String> e = iterator.next();
System.out.println(e.getKey() + "\t" + e.getValue());
}
Key是配置项name
Value是配置值value