版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sima64/article/details/49456887
1. 使用Hadoop 的URL读取数据:使用URL打开一个数据流,从中读取数据.
static{
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
}
public static void main(String[] args){
InputStream input = null;
try{
input = new URL("hdfs://masterIP/path").openStream();
IOUtils.copyBytes(input,System.out,2048,false);
}finally{
input.close();
}
}
2. 使用FileSystem 读取数据.hadoop把一个文件视为一个 Path对象,把一个路径视为一个URI
获取FileSystem 有两种方法:
public static FileSystem get(Configuration conf)
默认返回本地文件系统.
public static FileSystem get(URI uri,Configuration conf)--->
使用指定的URI获取文件系统,如果指定的URI中没有指定的方案(即没有获得相应的文件系统),返回本地文件系统.
Configuratin 封装了一个服务端或者客户端的配置,用路径读取配置文件(conf/core.site.xml).
InputStream input = null;
try{
Configuration conf = new Configuration();
URI uri = URI.create("hdfs://192.168.1.128:9000/work/word.txt");
FileSystem fileSystem = FileSystem.get(uri, conf);
input = fileSystem.open(new Path("hdfs://192.168.1.128:9000/work/word.txt"));
IOUtils.copyBytes(input, System.out, 2048,false);
}catch(Exception e ){
e.printStackTrace();
}finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3.