通过eclipse操作HDFS集群

1.准备环境

  • 配置本机的HADOOP_HOME
  • 替换bin目录
  • 修改用户名,在环境变量中增加 HADOOP_USER_NAME
  • 导入jar包
  • 安装插件,方便在eclipse中操作HDFS集群。在eclipse安装目录中增加dropins/plugins目录,在里面添加一个hadoop-eclipse-plugin-2.6.0.jar包。然后重启eclipse。

2.Java API

  • 操作HDFS之前得先创建配置对象。Configuration conf = new Configuration(true);true代表要自动加载配置文件。所以在项目根目录下新建一个source文件,把Hadoop的hdfs-site.xml和core-site.xml文件放在里面
  • 创建操作HDFS的对象。FileSystem fs = FileSystem.get(conf);
  • 查看文件系统的内容。fs.listStatus(path);path是一个路径对象,返回一个数组。
  • 创建文件夹。fs.mkdirs(path);
  • 上传文件。fs.copyFromLocalFile(true,srcPath, destPath);true代表把本地的文件删除(相当于剪切),没有true代表不会删除本地的文件(相当与复制),srcPath是要上传的文件的路径(本地)。destPath是上传到哪的路径。(hdfs集群)。
  • 下载文件。fs.copyToLocalFile(true,srcPath, destPath);true的作用和上传文件中true一样。srcPath是要下载的文件的路径(HDFS集群)。destPath是下载到哪的路径(本地)。
  • 重命名。fs.rename(srcPath, destPath);srcPath原名,destPath新名。
  • 内部复制。FileUtil.copy(srcPath.getFileSystem(conf), srcPath, destPath.getFileSystem(conf), destPath,false, conf);
  • 内部移动。FileUtil.copy(srcPath.getFileSystem(conf), srcPath, destPath.getFileSystem(conf), destPath,true, conf);
  • 创建一个新文件。fs.createNewFile(path);path是文件的路径。
  • 写文件。 FSDataOutputStream outputStream = fs.create(path);path是文件的路径。 outputStream.write(content.getBytes(“UTF-8”));content是写的内容。这个方法相当于重写,就是文件中原来的内容就没有了。
  • 追加写。FSDataOutputStream append = fs.append(path);path是文件的路径。append.write(content.getBytes(“UTF-8”));content是写的内容。这个方法相当于追加,文件原来的内容还会保留,只是把新的内容追加到文件中。
  • 读文件内容。
private static void readFromHDFSFile(FileSystem fs, String string) throws IllegalArgumentException, IOException {
		FSDataInputStream inputStream = fs.open(new Path(string));
		
		FileStatus fileStatus = fs.getFileStatus(new Path(string));
	
		long len = fileStatus.getLen();
		
		byte[] b = new byte[(int)len];
		int read = inputStream.read(b);
		while(read != -1){
			System.out.println(new String(b));
			read = inputStream.read(b);
		}
		
		
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值