1.获取HDFS文件系统
public static FileSystem getFileSystem(){
//读取配置文件
Configuration conf = new Configuration();
//获取文件系统对象(在hadoop集群上运行)
//FileSystem fs = FileSystem.get(conf);
//在本地运行
URI uri = new URI("hdfs://hostname:9000");
FileSystem fs = FileSystem.get(uri,conf);
}
2.创建文件目录
public static void mkdir(){
//获取文件系统
FileSystem fs = getFileSystem();
//创建文件目录
fs.mkdir(new path(" "));
//释放资源
fs.close();
3.文件上传至HDFS
public static void copyToHDFS(){
FileSystem fs = getFileSystem();
//从···上传
Path srcpath = new Path(" ");
//上传到···
Path dstpath = new Path(" ");
//上传文件
fs.copyFromLocalFile(srcpath,dstpath);
//释放资源
fs.close();
4.从HDFS下载文件
public static void getFille(){
FileSystem fs = getFileSystem();
//从···上传
Path srcpath = new Path(" ");
//上传到···
Path dstpath = new Path(" ");
//上传文件
fs.copyToLacalFile(srcpath,dstpath);
//释放资源
fs.close();
5.获取目录下的所有文件
public static void ListAllFill(){
FileSystem fs = getFileSystem();
//列出目录内容
FileStatus[] status = fs.ListStatus(new Path(" "));
//获取目录下的所有文件路径
Path[] listedPaths = FileUtil.stat2Paths(status);
//循环输出目录文件
for(Path p : listedPaths){
System.out.println(p);
}
fs.close();
}
6.查看某个文件在HDFS集群的位置
public static void getFileLocal(){
FileSystem fs = getFileSystem();
//文件路径
Path path = new Path();
//获取文件目录
FileStatus fileStatus=fs.getFileStatus(path);
//获取文件块位置信息
BlockLocation[] blkLocation = fs.getFileBlockLocation(fileStatus,0,fileStatus.getln());
//循环输出块信息
for(int i=0;i<blkLocation.length;i++){
//获取所有节点信息
String[] hosts = blkLocation(i).getHosts();
System.out.println("block"+i+"_location"+hosts[0];
}
}
7.删除文件或者文件目录
public static void rmdir(){
FileSystem fs = getFileSystem();
fs.delete(new Path(" "),true);
fs.close();
8.获取HDFS集群节点信息
public static void getHDFSNodes(){
FileSystem fs = getFileSystem();
//获取分布式文件系统
DistributedFileSystem hdfs = (DistributedFileSystem)fs;
//获取所有节点
DataNodeInfo[] dataNodeStatus = hdfs.getDataNodeStats();
//循环打印所有节点
for(int i=0; i<dataNodeStatus.length;i++){
System.out.println("DataNode_"+i+"_Name:"+dataNodeStatus[i].getHostName();
}
}