【笔记】JAVA API 访问 HDFS

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();
   }
}   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值