hadoop-2 HDFS API

来源:互联网 发布:天龙八部mac版下载 编辑:程序博客网 时间:2024/05/16 09:18
  • 1.HDFS读取数据

 1. 使用Hadoop 的URL读取数据:使用URL打开一个数据流,从中读取数据.    /*需要FsUrlStreamHandlerFactory实例来调用在URL中的setURLStreamHandlerFactory方法    *   该方法在一个java虚拟机中只能调用一次,因此放在一个静态方法中.    */    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);        //该方法默认使用4KB缓冲区.        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. 
0 0
原创粉丝点击