hadoop学习之JavaAPI

1.首先需要引入hadoop的maven依赖

        
            org.apache.hadoop
            hadoop-common
            2.7.4
        
        
            org.apache.hadoop
            hadoop-hdfs
            2.7.4
        
        
            org.apache.hadoop
            hadoop-client
            2.7.4
        

2.连接到hdfs文件系统

//创建一个配置类
Configuration conf = new Configuration();

//创建一个访问hdfs的客户端对象
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop-node1:9000"), conf, "root"); //指定用户

3.API命令
文件创建

fs.creat(new path("/user/yang/a.txt"))

查看所有的文件


Configuration conf = new Configuration();

//创建一个访问hdfs的访问对象
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop-node1:9000"), conf, "root");

//得到所有的文件
RemoteIterator list = fs.listFiles(new Path("/"), true);
while(list.hasNext())
{
     	 //显示其中一个文件
		LocatedFileStatus next = list.next();
		//文件的名字
		System.out.println(next.getPath().getName());
		//得到块的大小
		System.out.println(next.getBlockSize());
		//得到文件的读写权限
		System.out.println(next.getPermission());
		//获取文件的所有者
		System.out.println(next.getOwner());
		//得到文件的大小
		System.out.println(next.getLen());

		BlockLocation[] locations = next.getBlockLocations();

		for (BlockLocation location : locations) {
				//block-length表示块的大小,block-offset表示偏移量
				System.out.println("block-length"+location.getLength()+",block-offset"+location.getOffset());
				String[] hosts = location.getHosts();
				for (String host : hosts) {
			//查看备份的所在主机
				System.out.println(host);
		}
}

System.out.println("-----------------------------------");
}

查看当前的文件和文件夹

Configuration conf = new Configuration();

FileSystem fs = FileSystem.get(new URI("hdfs://hadoop-node1:9000"), conf, "root");

FileStatus[] listStatus = fs.listStatus(new Path("/"));


String flag="f--";
for (FileStatus status : listStatus) {
if(status.isFile())
{
		flag="f--";
}
else {
		flag="d--";
}
System.out.println(flag+status.getPath().getName());
System.out.println(status.getPermission())

目录操作

创建目录
     fs.mkdirs(new Path("/user/yang/java-test"));
删除目录
     fs.delete(new Path("/user/yang/test"),true);//true表示递归删除
重命名目录
     fs.rename(new Path("/user/yang/test"),new Path("/user/yang/test01"));
   //前面的是原来的名字,后面是要改的名字

你可能感兴趣的:(hadoop学习之JavaAPI)