常用HDFS操作

  • 向HDFS中上传任意文本文件,如果指定的文件在HDFS中已经存在,由用户指定是追加到原有文件末尾还是覆盖原有的文件;
    在这里插入图片描述
//假设  /user/hadoop/input路径已存在 如没存在 在命令行输入 hadoop fs -mkdir -p /user/hadoop/input
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://localhost:9000");
String localFileName = "/home/hadoop/myfile.txt";
String remoteFileName = "/user/hadoop/input/myfile.txt";
Path localFilePath = new Path(localFileName);
Path remoteFilePath = new Path(remoteFileName);
FileSystem fs = FileSystem.get(conf);
		
if(!fs.exists(remoteFilePath)) {   ////远程文件不存在
		System.out.println("文件未在远程服务器存在");
		fs.copyFromLocalFile(localFilePath, remoteFilePath);
		System.out.println("文件已上传到服务器");
}else {   //远程文件已存在
		System.out.println("文件已在远程服务器存在,请选择下一步动作:1 覆盖 ;2  添加到文件末尾 ");
		int choice = 0;
		Scanner input  = new Scanner(System.in);
		choice = input.nextInt();
		switch(choice) {
		case 1:fs.copyFromLocalFile(true, false, localFilePath,remoteFilePath);
					System.out.println("文件已成功进行覆盖");break;
		case 2:FSDataOutputStream out = fs.append(remoteFilePath);
			   FileInputStream in = new FileInputStream(localFileName); //字节流
				byte buff[] = new byte[1024];
				int read = -1;
				while((read =in.read(buff))>0) {  //in.read()返回读取数据的长度
					out.write(buff, 0, read);
				}
				out.close();
				in.close();
				System.out.println("内容已添加到文件末尾");break;
			default:System.out.println("未采取任何动作");break;
			}
		}
  • 从HDFS中下载指定文件,如果本地文件与要下载的文件名称相同,则自动对下载的文件重命名;
    在这里插入图片描述
    在这里插入图片描述

  • 将HDFS中指定文件的内容输出到终端中;
    这个命令特别简单:hadoop fs -cat /user/hadoop/input/myfile.txt
    在这里插入图片描述

  • 显示HDFS中指定的文件的读写权限、大小、创建时间、路径等信息;
    这个要求用shell实现也特别简单:hadoop fs -ls /user/hadoop/input/myfile.txt
    在这里插入图片描述

  • 给定HDFS中某一个目录,输出该目录下的所有文件的读写权限、大小、创建时间、路径等信息,如果该文件是目录,则递归输出该目录下所有文件相关信息;
    这个问题与上一个问题的不同之处在于目录里有目录:hadoop fs -ls -R -h /user/hadoop/input/
    在这里插入图片描述

  • 提供一个HDFS内的文件的路径,对该文件进行创建和删除操作。如果文件所在目录不存在,则自动创建目录;
    在这里插入图片描述

在这里插入图片描述

  • 提供一个HDFS的目录的路径,对该目录进行创建和删除操作。创建目录时,如果目录文件所在目录不存在则自动创建相应目录;删除目录时,由用户指定当该目录不为空时是否还删除该目录;
    shell:在这里插入图片描述
    在这里插入图片描述

  • 向HDFS中指定的文件追加内容,由用户指定内容追加到原有文件的开头或结尾;
    在这里插入图片描述
    在这里插入图片描述

  • 删除HDFS中指定的文件;
    shell命令:hadoo[ fs -rm /user/hadoop/input/myfile.txt
    在这里插入图片描述

  • 在HDFS中,将文件从源路径移动到目的路径。
    shell:hadoop fs -mv /user/hadoop/input/myfile.txt /user/hadoop/myfile.txt
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Leader_wang/article/details/83001819