Hadoop1.1.2学习笔记(4)

来源:互联网 发布:淘宝儿童摇摆车扭扭车 编辑:程序博客网 时间:2024/06/06 20:41

使用Java API进行Hadoop HDFS操作

获取FileSystem实例,对HDFS的所有操作都使用该实例。

        private static FileSystem getFileSystem() throws URISyntaxException,IOException {Configuration conf = new Configuration();URI uri = new URI("hdfs://hadoop2:9000");final FileSystem fileSystem = FileSystem.get(uri , conf);return fileSystem;}
首先新建一个hello文件,上传到HDFS上,使用:hadoop fs -put hello / 命令。然后使用下方代码读取打印到控制台
        /**  * 读取文件,调用fileSystem的open(path)  * @throws Exception  */private static void readFile() throws Exception {FileSystem fileSystem = getFileSystem();FSDataInputStream openStream = fileSystem.open(new Path("hdfs://hadoop2:9000/hello"));IOUtils.copyBytes(openStream, System.out, 1024, false);IOUtils.closeStream(openStream);}

        /** * 创建目录,调用fileSystem的mkdirs(path) * @throws Exception */private static void mkdir() throws Exception {FileSystem fileSystem = getFileSystem();fileSystem.mkdirs(new Path("hdfs://hadoop2:9000/aaa"));}/** * 删除目录,调用fileSystem的deleteOnExit(path) * @throws Exception */private static void rmdir() throws Exception {FileSystem fileSystem = getFileSystem();fileSystem.delete(new Path("hdfs://hadoop2:9000/aaa"));}

        /** * 遍历目录,使用FileSystem的listStatus(path) * 如果要查看file状态,使用FileStatus对象 * @throws Exception */private static void list() throws Exception{FileSystem fileSystem = getFileSystem();FileStatus[] listStatus = fileSystem.listStatus(new Path("hdfs://hadoop2:9000/"));for (FileStatus fileStatus : listStatus) {String isDir = fileStatus.isDir()?"目录":"文件";String name = fileStatus.getPath().toString();System.out.println(isDir+"  "+name);}}





0 0