通过JAVA API 来操作HDFS

导入依赖

		<dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.7.3</version>
        </dependency>

从本地上传文件到hdfs

导包:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
import java.net.URI;
public void testUpload() throws Exception{
        //1.读取hadoop的配置文件
        Configuration entries = new Configuration();
        //2.得到FileSystem对象
        //uri:表示你连接到哪一个hdfs
        //如果发现上传文件大小都是0kb,这是因为datanode所在机器的防火墙没有关闭
        FileSystem root = FileSystem.get(new URI("hdfs://192.168.200.161:9000"), entries, "root");
        //从本地计算机上传文件到hdfs
        root.copyFromLocalFile(new Path("D:\\a.txt"),new Path("/"));
        root.close();
    }

运行结果:
通过JAVA API 来操作HDFS

从hdfs上下载文件

 public void testDown() throws Exception {
        Configuration entries = new Configuration();
        FileSystem root = FileSystem.get(new URI("hdfs://192.168.200.161:9000"), entries, "root");
        //参数:是否删除hdfs上的文件,文件下载地址,下载到哪个盘的地址,是否使用本地文件系统接收
        root.copyToLocalFile(false,new Path("/a.txt"),new Path("E:/"),true);
        root.close();
    }

删除hdfs上的文件

	public void testDelete() throws Exception {
        Configuration entries = new Configuration();
        FileSystem root = FileSystem.get(new URI("hdfs://192.168.200.161:9000"), entries, "root");
        //参数:删除文件的路径,false只能删除空目录,true可以删除非空目录
        root.delete(new Path("/a.txt"),true);
        root.close();
    }

在hdfs上创建文件夹

	public void testMkdir() throws Exception {
        Configuration entries = new Configuration();
        FileSystem root = FileSystem.get(new URI("hdfs://192.168.200.161:9000"), entries, "root");
        root.mkdirs(new Path("/aaa/bbb/ccc"));
        root.close();
    }

在hdfs上创建空的文件

	public void testTouchz() throws Exception {
        Configuration entries = new Configuration();
        FileSystem root = FileSystem.get(new URI("hdfs://192.168.200.161:9000"), entries, "root");
        root.createNewFile(new Path("/aaa/bbb/ccc/sss.txt"));
        root.close();
    }

遍历hdfs上某个目录下的所有文件

 	public void testList() throws Exception {
        list(new Path("/"));
    }

    private void list(Path path) throws Exception {
        Configuration entries = new Configuration();
        FileSystem root = FileSystem.get(new URI("hdfs://192.168.200.161:9000"), entries, "root");
        FileStatus[] fileStatuses = root.listStatus(path);
        for (FileStatus file:fileStatuses
             ) {
            if(file.isFile()){
                System.out.println(file.getPath().toString());
            }else{
                list(file.getPath());
            }
        }
        root.close();
    }