1、初始化配置信息:
@Test
public void init() throws IOException, URISyntaxException, InterruptedException {
Configuration configuration =new Configuration();
configuration.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
configuration.set("fs.defaultFS","uri");
fileSystem=FileSystem.get(new URI("uri"),configuration,"hadoop");//以Hadoop身份
}
2、创建目录上传下载文件及删除文件:
HDFS读数据
与namenode通信查找元数据,文件的数据块在哪台datanode上
选取最近一台datanode服务器建立socket流
Datanode发送数据(从磁盘读取数据流放入数据包发送出去)
客户端接收数据包 先缓存在磁盘 然后写入文件
Hdfa写数据
客户端向namenode发送请求 检查目标文件是否存在,检查目标父目录是否存在。
那么返回是否可以上传数据
客户端对文件进行分块,请求namenode该向那台datanode上传数据
Namenode返回哪台datanode
客户端向datanode请求发送数据,几台datanode建立pipeline
客户端读数据以packet为单位发送数据到第一台datanode,第一台收到packet后向第二台发送,第二台向第三台传,第一台每传入一个packet会放入一个应答队列。
第一个块传完后,重复步骤传第二个块。
@Test
public void upload() throws IOException, URISyntaxException, InterruptedException {
init();
fileSystem.delete(new Path("/input/a.txt"),true);//全部删除目录下文件
fileSystem.mkdirs(new Path("/input/a.txt"));//创建目录
fileSystem.copyFromLocalFile(new Path("files/a.txt"),new Path("hdfs://39.105.116.243:9000/input/"));//上传文件
Path path=new Path("hdfs://39.105.116.243:9000/input/x");//下载文件
FSDataInputStream dis=fileSystem.open(path);//下载文件
FileOutputStream fileOutputStream=new FileOutputStream("files/a.txt");
IOUtils.copy(dis,fileOutputStream);
fileSystem.copyToLocalFile(path,new Path("files/b.txt"));
}
3、查看文件目录:
/*
* 显示文件*/
@Test
public void show() throws InterruptedException, IOException, URISyntaxException {
init();
RemoteIterator<LocatedFileStatus> iterator= fileSystem.listFiles(new Path("/"),true);//递归显示文件
while (iterator.hasNext()){
LocatedFileStatus fileStatus=iterator.next();
String string=fileStatus.getPath().getName();
System.out.println(string);
}
}
/*
* 显示文件及文件夹*/
@Test
public void show1() throws InterruptedException, IOException, URISyntaxException {
init();
FileStatus[] fileStatuses=fileSystem.listStatus(new Path("/"));//显示文件夹
for (FileStatus status:fileStatuses){
String string=status.getPath().getName();
System.out.println(string);
}
}