在使用MapReduce框架进行开发时,总会使用Configuration类的一个实例对象去初始化一个任务,然后进行任务提交,而在整个任务执行过程中,客户点实例化的Configuration的对象,将作为整个任务过程中参数版本,任务执行过程中所需要的所有参数都是从客户端实例化的Configuration对象中进行获取。
Configuration初始化时主要有两步:读取默认文件和读取site级别的文件。Configuration初始化过程中,首先会读取整个CLASSPATH中的CORE-DEFAULT.XML、HDFS-DEFAULT.XML、YARN-DEFAULT.XML以及默认配置文件。
0. 前期配置
FileSystem fs = null;
@Before
publicvoid init() throws Exception{
//读取classpath下的xxx-site.xml 配置文件,并解析其内容,封装到conf对象中
Configuration conf = new Configuration();
//也可以在代码中对conf中的配置信息进行手动设置,会覆盖掉配置文件中的读取的值
conf.set("fs.defaultFS", "hdfs://192.168.19.39:9000/");
//根据配置信息,去获取一个具体文件系统的客户端操作实例对象
fs = FileSystem.get(new URI("hdfs:// 192.168.19.39:9000/"),conf,"hadoop");
}
1. 上传文件,比较底层的写法
publicvoid upload() throws Exception {
Configurationconf = new Configuration();
conf.set("fs.defaultFS", "hdfs:// 192.168.19.39:9000/");
FileSystemfs = FileSystem.get(conf);
Pathdst = new Path("hdfs:// 192.168.19.39:9000/zg/x.txt");
FSDataOutputStreamos = fs.create(dst);
FileInputStreamis = new FileInputStream("c:/x.txt");
IOUtils.copy(is, os);
}
2. 上传文件,封装好的写法
publicvoid upload2() throws Exception, IOException{
fs.copyFromLocalFile(new Path("c:/x.txt"), new Path("hdfs:// 192.168.19.39:9000/aaa/bbb/ccc/x2.txt"));
}
3. 下载文件
publicvoid download() throws Exception {
fs.copyToLocalFile(new Path("hdfs:// 192.168.19.39:9000/aa/x2.txt"), new Path("c:/x2.txt"));
}
4. 查看文件信息
public void listFiles() throws FileNotFoundException, IllegalArgumentException, IOException {
// listFiles列出的是文件信息,而且提供递归遍历
RemoteIterator<LocatedFileStatus> files = fs.listFiles(new Path("/"), true);
while(files.hasNext()){
LocatedFileStatus file = files.next();
Path filePath = file.getPath();
String fileName = filePath.getName();
System.out.println(fileName);
}
System.out.println("---------------------------------");
//listStatus 可以列出文件和文件夹的信息,但是不提供自带的递归遍历
FileStatus[] listStatus = fs.listStatus(new Path("/"));
for(FileStatus status: listStatus){
String name = status.getPath().getName();
System.out.println(name + (status.isDirectory()?" is dir":" is file"));
}
}
5. 创建文件夹
public void mkdir() throws IllegalArgumentException, Exception {
fs.mkdirs(new Path("/aaa/bbb/ccc"));
}
6. 删除文件或文件夹
public void rm() throws IllegalArgumentException, IOException {
fs.delete(new Path("/aa"), true); //true指的是递归删除
}