HADOOP文件系统API练习

/**
* 合并本地文件流到hdfs上
*/
public static void write() {
Configuration conf = new Configuration();
Path localDir = new Path("/test");
Path hdfsDir = new Path("/user/xingluo1/test");

    try {
        FileSystem local = FileSystem.getLocal(conf);
        FileSystem hdfs = FileSystem.get(URI.create("hdfs://192.168.109.198:9000/"), conf);

        FileStatus[] files = local.listStatus(localDir);
        FSDataOutputStream out = hdfs.create(hdfsDir);
        for (FileStatus file : files) {
            System.out.println("path :" + file.getPath());
            FSDataInputStream in = local.open(file.getPath());
            byte[] bytes = new byte[256];
            int bytesNum = 0;
            while ((bytesNum = in.read(bytes)) > 0) {
                out.write(bytes, 0, bytesNum);
            }
            in.close();
        }
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//增删改查
public static void hdfsTest() {
    Configuration conf = new Configuration();
    Path path = new Path("/test1");
    try {
        FileSystem hdfs = FileSystem.get(URI.create("hdfs://192.168.109.198:9000/"), conf);
        boolean bool = hdfs.exists(path);
        System.out.println(path.getName() + "文件夹是否存在:" + bool);
        if (!bool) {
            System.out.println("创建文件夹:" + path.getName());
            hdfs.mkdirs(path);
        }

        //列出根目录下所有文件和目录
        FileStatus[] files = hdfs.listStatus(new Path("/"));
        for (FileStatus file : files) {
            System.out.println(file.getPath());
        }

        bool = hdfs.delete(new Path("/user/xingluo1/"), true);
        System.out.println("是否删除成功:" + bool);

        bool = hdfs.rename(new Path("/user/xingluo/hebing6"),new Path("/user/hebing6"));
        System.out.println("是否重命名成功:" + bool);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Hadoop中用作文件操作的主类位于org.apche.hadoop.fs软件包中。hadoop的基本文件操作包括常见的open,read,write,close。hadoop的文件API是通用的,可用于HDFS之外的其他文件系统。

FileSystem类:起点类,与文件系统交互的抽象类,具体实现子类来处理HDFS和本地文件系统,可以通过调用工厂方法

FileSystem.get(Configuration conf)

获取FileSystem实例

Configuration:保留键/值配置参数的特殊类。默认实例化方法是以HDFS系统 的资源配置为基础的。可以通过以下方法得到与HDFS接口的FileSystem对象

Configuration conf = new Configuration();
FileSystem hdfs = FileSystem.get(conf);

要得到本地文件系统FileSystem对象

FileSystem local = FileSystem.getLocal(conf);

Path对象表示文件和目录
FileStatus对象存储文件和目录的元数据
FileSystem.listStatus() 得到一个目录中文件列表

Path inputDir = new Path(args[0]);
FileStatus[] inputFiles = local.listStatus(inputDir);

FSDataInputStream访问Path读取文件

 FSDataInputStream in = local.open(file.getPath());
            byte[] bytes = new byte[256];
            int bytesNum = 0;
            while ((bytesNum = in.read(bytes)) > 0) {
                ...
            }
            in.close();

FSDataOutputStream写入数据

 Path hdfsDir = new Path(args[1]);
 FSDataOutputStream out = hdfs.create(hdfsDir);
 out.write(bytes, 0, bytesNum);
 out.close();
posted @ 2018-08-22 13:52  爪哇岛求生记  阅读(431)  评论(0编辑  收藏  举报