大数据地阶斗技--HDFS java API编程

目录

一.获取文件系统

二.列出所有DataNode的名字信息

三.创建文件目录

四.删除文件或文件目录

五.查看文件是否存在

六.文件上传至HDFS

七.从HDFS下载文件

八.文件重命名

九.遍历目录和文件

十.获取数据块所在的位置

十一.根据filter获取目录下的文件


一.获取文件系统

        如果远程登录没有文件系统的权限,可以使用System.setProperty("HADOOP_USER_NAME","root")解决该问题。

 public static FileSystem getFileSystem() {
        // 读取配置文件
    Configuration conf=new Configuration();
    // 文件系统
    FileSystem fs=null;
    conf.set("fs.defaultFS","hdfs://192.168.254128:9000");
    System.setProperty("HADOOP_USER_NAME","root");
    try{
        fs=FileSystem.get(conf);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fs;
    }

二.列出所有DataNode的名字信息

        通过DistributedFileSystem类可以访问分布在不同节点上的DataNode,通过DatanodeInfo.getHostName()方法可以获取HDFS集群上的所有节点名称

 public static void listDataNode(){
        try{
            Configuration conf=new Configuration();
            conf.set("fs.defaultFS","hdfs://192.168.254.128:9000");
            System.setProperty("HADOOP_USER_NAME","root");
            FileSystem fs=FileSystem.get(conf);
            DistributedFileSystem hdfs=(DistributedFileSystem) fs;
            DatanodeInfo[] dataNodeStats=hdfs.getDataNodeStats();
            String[] names=new String[dataNodeStats.length];
            System.out.println("所有DataNode名字信息:");

            for (int i=0;i< names.length;i++){
                names[i]=dataNodeStats[i].getHostName();
                System.out.println(names[i]);
            }
            System.out.println(hdfs.getUri().toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

三.创建文件目录

        创建文件目录通过mkdirs方法实现,该方法会返回一个布尔值,表示创建文件夹是否成功

  public static void mkdir(String path)throws IOException{
        Configuration conf=new Configuration();
        conf.set("fs.defaultFS","hdfs://192.168.254.128:9000");
        System.setProperty("HADOOP_USER_NAME","root");
        FileSystem fs=FileSystem.get(conf);
        Path srcPath=new Path(path);
        boolean isok= fs.mkdirs(srcPath);
        if(isok){
            System.out.println("create dir ok");
        }else {
            System.out.println("create dir failure");
        }
        fs.close();
    }

四.删除文件或文件目录

        删除文件或文件目录可以使用deleOnExit方法实现,该方法会返回一个布尔值,表示删除文件或文件夹是否成功

  public static void delete(String filePath)throws IOException{
        Configuration conf=new Configuration();
        conf.set("fs.defaultFS","hdfs://192.168.254:9000");
        System.setProperty("HADOOP_USER_NAME","root");
        FileSystem fs=FileSystem.get(conf);
        Path path=new Path(filePath);
        boolean isok=fs.deleteOnExit(path);
        if(isok){
            System.out.println("delete ok!");
        }else{
            System.out.println("delete failure");
        }
        fs.close();
    }

五.查看文件是否存在

        判断文件或文件夹是否存在可以使用exists方法,该方法返回一个布尔值

  public static void checkFileExist(Path path) {
        try {
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", "hdfs://192.168.254.128:9000");
            System.setProperty("HADOOP_USER_NAME", "root");
            FileSystem fs = FileSystem.get(conf);
            DistributedFileSystem hdfs = (DistributedFileSystem) fs;
            Path f = hdfs.getHomeDirectory();
            System.out.println("main path:" + f.toString());
            boolean exit = fs.exists(path);
            System.out.println("Whether exist of this file:" + exit);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

六.文件上传至HDFS

        copyFromLocalFile表示文件的复制,该方法有三个参数:第一个参数是布尔值,表示是否删除源文件,true表示删除,false表示不删除;第二个参数是要复制的文件;第三个参数是要复制到的目的地

  public static void uploadFile(String src,String dst)throws IOException,URISyntaxException{
        Configuration conf=new Configuration();
        FileSystem fs=FileSystem.get(new URI("hdfs://192.168.254.128:9000"),conf);
//        FileSystem fs=FileSystem.get(conf);
        Path srcPath=new Path(src); //源路径
        Path dstPath=new Path(dst); //目标路径
        fs.copyFromLocalFile(false,srcPath,dstPath);
        fs.close();
    }

七.从HDFS下载文件

        copyToLocalFile表示从HDFS下载文件到本地系统该方法有两个参数,第一个参数表示要下载的HDFS文件,第二个表示要下载到的文件或目录

  /**
     * 从HDFS下载文件,remote hdfs文件,local 目的地
     */
    public static void download(String remote,String local)throws IOException, URISyntaxException {
        Configuration conf=new Configuration();
        Path path=new Path(remote);
        FileSystem fs=FileSystem.get(new URI("hdfs://192.168.254.128:9000"),conf);
        fs.copyToLocalFile(path,new Path(local));
        System.out.println("从"+remote+"下载到"+local);
        fs.close();
    }

八.文件重命名

        重命名文件可以使用rename方法

public static void rename(String oldName,String newName)throws IOException{
        Configuration conf=new Configuration();
        conf.set("fs.defaultFS","hdfs://192.168.254.128:9000");
        System.setProperty("HADOOP_USER_NAME","root");
        FileSystem fs=FileSystem.get(conf);
        Path oldpath=new Path(oldName);
        Path newPath=new Path(newName);
        boolean isok=fs.rename(oldpath,newPath);
        if(isok){
            System.out.println("重命名成功!");
        }else {
            System.out.println("重命名失败!");
        }
        fs.close();
    }

九.遍历目录和文件

        FileStatus包含了HDFS文件的常用信息,而该对象的使用需要通过DistributedFileSystem对象来访问,因此需要先将FileSystem对象强制转换为DistributedFileSystem

  private static void showDir(Path path)throws Exception{
        Configuration conf=new Configuration();
        conf.set("fs.defaultFS","hdfs://198.168.254.128:9000");
        System.setProperty("HADOOP_USER_NAME","root");
        FileSystem fs=FileSystem.get(conf);
        DistributedFileSystem hdfs=(DistributedFileSystem) fs;
        FileStatus[] fileStatuses=hdfs.listStatus(path);
        if(fileStatuses.length>0){
            for(FileStatus status:fileStatuses){
                Path f=status.getPath();
                System.out.println(f);
                if(status.isDir()){
                    FileStatus[] files= hdfs.listStatus(f);
                    if(files.length>0){
                        for(FileStatus file:files)
                            showDir(file.getPath());
                    }
                }
            }
        }
    }

十.获取数据块所在的位置

        通过FileSystem.getFileBlockLocation(FileStatus file,long start,long len)可以查找指定文件在HDFS集群上的位置,其中file为文件的完整路径,start和len来标识文件的路径

 public static void getLocation(Path path){
        try{
            Configuration conf=new Configuration();
            conf.set("fs.defaultFS","hdfs://192.168.254.128:9000");
            System.setProperty("HADOOP_USER_NAME","root");
            FileSystem fs=FileSystem.get(conf);
            FileStatus fileStatus=fs.getFileStatus(path);
            BlockLocation[] blockLocations=fs.getFileBlockLocations(fileStatus,0,fileStatus.getLen());
            for(BlockLocation currentLocation:blockLocations){
                String[] hosts=currentLocation.getHosts();
                for(String host:hosts){
                    System.out.println(host);
                }
            }
            // 取得最后修改时间
            long modifyTime=fileStatus.getModificationTime();
            Date d=new Date(modifyTime);
            System.out.println(d);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

十一.根据filter获取目录下的文件

        HDFS提供globStatus方法对文件路径进行过滤,可以提供使用通配符的方式指定输入,无需列举所有文件或目录来指定输入,hadoop通配符方法有两个:

public FileStatus[] globStatus(Path pathPattern)throw IOException

public FileStatus[] globStatus(Path pathPattern,PathFilter filter)throw IOException

globStatus()方法返回与路径相匹配的所有文件的FileStatus对象数组,并按路径排序

 public class RegexExcludePathFilter implements PathFilter{
        private final String regex;
        public RegexExcludePathFilter(String regex){
            this.regex=regex;
        }
        @Override
        public boolean accept(Path path) {
            return false;
        }
    }

    public void list()throws IOException{
        Configuration conf=new Configuration();
        conf.set("fs.defaultFS","hdfs://192.168.254.128:9000");
        System.setProperty("HADOOP_USER_NAME","root");
        FileSystem fs=FileSystem.get(conf);
        // PathFilter是过滤不符合置顶表达式的路径,下列就是把以txt结尾的过滤掉
        FileStatus[] statuses=fs.globStatus(new Path("/data/*"),
                new RegexExcludePathFilter(".*txt"));
        Path[] listedPaths=FileUtil.stat2Paths(statuses);
        for(Path p:listedPaths){
            System.out.println(p);
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_63009369/article/details/130651652