删除文件/目录
通过`FileSystem.delete(Path f,Boolean recursive)`可删除指定的 HDFS 文件或目录,其中 `f` 为需要删除文件或目录的完整路径,`recursive` 用来确定是否进行递归删除,若是删除文件则为 `false`,若是删除的是目录则为 `True`。具体实现如下:
packagecom.xiaowang.hdfs; importjava.io.IOException; importjava.net.URI; importjava.net.URISyntaxException; importorg.apache.hadoop.conf.Configuration; importorg.apache.hadoop.fs.FileSystem; importorg.apache.hadoop.fs.Path; importorg.junit.After; importorg.junit.Before; importorg.junit.Test; publicclassHDFSDemo { FileSystemfs=null; // 每次执行单元测试前都会执行该方法publicvoidsetUp() throwsIOException, InterruptedException, URISyntaxException { Configurationconf=newConfiguration(); // 不需要配置“fs.defaultFS”参数,直接传入URI和用户身份,最后一个参数是安装Hadoop集群的用户,我的是“root”fs=FileSystem.get(newURI("hdfs://localhost:9000"), conf, "root"); } //单元方法:删除文件或者文件夹publicvoiddeleteFileOrDir() throwsIllegalArgumentException, IOException{ //删除文件,第二参数:是否递归,若是文件或者空文件夹时可以为false,若是非空文件夹则需要为truefs.delete(newPath("/123/read.txt"),false); //删除文件夹fs.delete(newPath("/123/data"), true); } // 每次执行单元测试后都会执行该方法,关闭资源publicvoidtearDown() { if (null!=fs) { try { fs.close(); } catch (IOExceptione) { e.printStackTrace(); } } } }
查看指定路径中文件和块信息
通过`FileSystem.listFiles(Path f,Boolean recursive)`可递归获取指定 HDFS 目录下的所有文件的绝对路径,其中 `f` 为指定路径,`recursive` 用来确定是否进行递归列出。具体实现如下:
importjava.io.FileNotFoundException; importorg.apache.hadoop.fs.BlockLocation; importorg.apache.hadoop.fs.LocatedFileStatus; importorg.apache.hadoop.fs.RemoteIterator; //单元方法:查看目录信息,只显示该目录下的文件信息publicvoidlistFiles() throwsFileNotFoundException, IllegalArgumentException, IOException{ //使用迭代器递归获取该目录下的所有文件RemoteIterator<LocatedFileStatus>listfile=fs.listFiles(newPath("/123"), true); while(listfile.hasNext()){ LocatedFileStatusfileStatus=listfile.next(); System.out.println("文件路径:"+fileStatus.getPath()); System.out.println("文件名称:"+fileStatus.getPath().getName()); System.out.println("块的大小:"+fileStatus.getBlockSize()); System.out.println("文件所有者:"+fileStatus.getOwner()); System.out.println("文件所属组:"+fileStatus.getGroup()); System.out.println("文件权限:"+fileStatus.getPermission()); System.out.println("副本个数:"+fileStatus.getReplication()); System.out.println("文件长度:"+fileStatus.getLen()); System.out.println("-----块的信息-----"); BlockLocation[] blockLocations=fileStatus.getBlockLocations(); for(BlockLocationbLocation:blockLocations){ System.out.println("块的长度:"+bLocation.getLength()+"\t块起始偏移量:"+bLocation.getOffset()); //块所在的DataNode节点String[] hosts=bLocation.getHosts(); System.out.print("DataNode: "); for(Stringstr:hosts){ System.out.print(str+"\t"); } System.out.println(); } System.out.println("------------------------"); } }