1、要从HDFS文件系统中读取文件,最简单的就是使用Java.net.URL对象打开数据流读取数据
2、要让Java程序识别Hadoop的HDFS的URL,需采用FsUrlStreamHandlerFactory实例调用URL中的setURLStreamHandlerFactory方法,(JVM只调用一次上述方法,因此可考虑设为static方法)
static{
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
}
InputStream is=null;
is=new URL(args[0]).openStream();
IOUtils.copyBytes(is,System.out,4096,false);
3、FileSystem是一个抽象类,需要被继承,有两个静态get()方法
其中之一:public static FileSystem get(URL url,Configuration conf)
Configuration conf=new Configuration();
String url=args[0];
FileSystem fs=FileSystem.get(URI.create(url),conf);
InputStream is=fs.open(new Path(url));
IOUtils.copyBytes(is,System.out,4096,false);
4、FileCopy
String localPath=arg[0];//源路径
String toPath=arg[1];//目标路径
InputStream is=new BufferedInputStream(new FileInput(localPath));//创建输入流
Configuration conf=new Configuration();//配置文化
FileSystem fs=FileSystem.get(URI.create(toPath),conf);
OutputStream os=fs.create(new Path(toPath));//创建输出流
IOUtils.copyBytes(is,os,4096,true);//复制内容
5、HDFS实例,即DistributedFileSystem,应该继承FileSystem 抽象类,
写过程:conf.set(xx);conf.set(xx);fs=FileSystem.get(conf);fs.put(xx);
读过程:fs=FileSystem.get(conf);fs.copyToLocal(xx);