彷徨 | HDFS客户端API编程基本java操作 | 二

一 : API编程查看文件内容

先上传一文件到HDFS

hadoop fs -put ./zhang /

查看文件是否传上去

hadoop fs -ls /

用命令行客户端查看文件内容

用API编程查看文件内容

代码 : 

	//  读取HDFS中的文件的内容
	@Test
	public void testReadContent() throws Exception {
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS", "hdfs://marshal:9000/");
		FileSystem fs = FileSystem.get(conf);
		
		FSDataInputStream in = fs.open(new Path("/zhang"));
		
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String line=null;
		while((line=br.readLine())!=null) {
			System.out.println(line);
		}
		
		br.close();
		in.close();
		fs.close();
	}

结果 : 

二 : API编程读取HDFS中的文件的指定偏移量范围内的数据内容

上传一个文件zhang2

查看文件内容 : 

API编程产看文件偏移量指定内容

代码 : 

	//  读取HDFS中的文件的指定偏移量范围内的数据内容
	@Test
	public void testReadContent2() throws Exception {
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS", "hdfs://marshal:9000/");
		FileSystem fs = FileSystem.get(conf);
		
		FSDataInputStream in = fs.open(new Path("/zhang2"));
		in.seek(60);
		// 读/qingshu.txt中的从60偏移量开始的数据,总共20个字节
		byte[] b = new byte[4];
		int read = -1;
		long count = 0;
		while((read=in.read(b))!=-1) {
			System.out.print(new String(b,0,read));
			count += read;
			if(count==20) {
				break;
			}
		}
		
		in.close();
		fs.close();
	}

结果 : 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值