- 概述
hadoop中关于文件操作类基本上全部是在org.apache.hadoop.fs包中,这些api能够支持的操作包含:打开文件,读写文件,删除文件等。
hadoop类库中最终面向用户提供的接口类是FileSystem,该类是个抽象类,只能通过来类的get方法得到具体类。get方法存在几个重载版本,常用的是这个:
static FileSystem get(Configuration conf);
该类封装了几乎所有的文件操作,例如mkdir,delete等。综上基本上可以得出操作文件的程序库框架:
operator()
{
得到Configuration对象
得到FileSystem对象
进行文件操作
}
- 文件操作
1. 新建java项目并导包
2. 写测试类
2.1. 上传本地文件到hdsf
@Test
public void upload() throws IOException, InterruptedException, URISyntaxException{
//1.实例化系统需求配置
Configuration configuration=new Configuration();
// 2。获取文件系统操作的客户端实例对象
FileSystem fs=FileSystem.get(new URI("hdfs://192.168.233.128:9000"), configuration, "root");
//3.执行上传操作
fs.copyFromLocalFile(new Path("d:\\test.txt"),new Path( "/test.txt"));
//4.关闭链接
fs.close();
}
2.2. 下载文件到本地
@Test
public void downLoad() throws IOException, InterruptedException, URISyntaxException{
//1.实例化系统需求配置
Configuration configuration=new Configuration();
// 2。获取文件系统操作的客户端实例对象
FileSystem fs=FileSystem.get(new URI("hdfs://192.168.233.128:9000"), configuration, "root");
//3.执行下载操作
//fs.copyToLocalFile(delSrc, src, dst, useRawLocalFileSystem);
fs.copyToLocalFile(false, new Path("/test.txt"), new Path("E://test.txt"),true);
//4.关闭链接
fs.close();
}
2.3. 删除hdfs上的文件
@Test
public void delete() throws IOException, InterruptedException, URISyntaxException{
//1.实例化系统需求配置
Configuration configuration=new Configuration();
// 2。获取文件系统操作的客户端实例对象
FileSystem fs=FileSystem.get(new URI("hdfs://192.168.233.128:9000"), configuration, "root");
//3.执行删除
//delete 默认为true,false时只能删除空的文件夹==
fs.delete(new Path("/test.txt"),true);
//4.关闭链接
fs.close();
}
2.4. 创建目录
@Test
public void mkdir() throws IOException, InterruptedException, URISyntaxException{
//1.实例化系统需求配置
Configuration configuration=new Configuration();
// 2。获取文件系统操作的客户端实例对象
FileSystem fs=FileSystem.get(new URI("hdfs://192.168.233.128:9000"), configuration, "root");
//3创建目录
fs.mkdirs(new Path("/usr/local"));
//4.关闭链接
fs.close();
}
2.5. 遍历文件
@Test
public void list() throws IOException, InterruptedException, URISyntaxException{
//1.实例化系统需求配置
Configuration configuration=new Configuration();
// 2。获取文件系统操作的客户端实例对象
FileSystem fs=FileSystem.get(new URI("hdfs://192.168.233.128:9000"), configuration, "root");
//3遍历
FileStatus [] status=fs.listStatus(new Path("/"));
for(int i=0;i<status.length;i++){
if(status[i].isFile()){
System.out.println("文件:"+status[i].getPath().toString());
}else if(status[i].isDirectory()){
System.out.println("目录:"+status[i].getPath().toString());
}
}
//4.关闭链接
fs.close();
}