HDFS API的简单使用(2)

本文提供两个示例程序,分别使用Hadoop FileSystem API和Hadoop URL方式从HDFS中读取数据,并展示如何将读取的数据打印到标准输出。这两个示例有助于理解Hadoop文件系统的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.framelife.hadoop;

import java.io.IOException;
import java.io.InputStream;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;

/**
 * 使用FileSystem API读取数据
 * @author 潘广伟
 *
 */
public class FileSystemCat {
	public static Configuration getConf(){
		Configuration configuration = new Configuration();
		configuration.addResource(new Path("core-site.xml"));
		configuration.addResource(new Path("hdfs-site.xml"));
		return configuration;
	}

	public static void main(String[] args) {
		InputStream in = null;
		String url = "hdfs://namenode:9000/user/hadoop/hello1.txt";
		try {
			FileSystem fs = FileSystem.get(getConf());
			in = fs.open(new Path(url));
			
			IOUtils.copyBytes(in, System.out, in.available(), false);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeStream(in);
		}
	}

}



package cn.framelife.hadoop;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;
import org.apache.hadoop.io.IOUtils;

/**
 * 使用Hadoop URL读取数据
 * @author 潘广伟
 *
 */
public class URLCat {
	static{
		URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
	}
	
	public static void main(String[] args) {
		InputStream in = null;
		String url = "hdfs://namenode:9000/user/hadoop/hello1.txt";
		try {
			in = new URL(url).openStream();
			
			byte[] b = new byte[in.available()];
			in.read(b, 0, in.available());
			String msg = new String(b);
			
			System.out.println("接收到的信息:"+msg);
			
			//下面是通过IOUtils工具把输入流中的数据使用系统输出
//			IOUtils.copyBytes(in, System.out, 4096, false);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeStream(in);
		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值