HDFS API入门-----Hello World

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import java.io.IOException;

public class FileSystemAPIDemo {
    public static void main(String[] args) throws IOException {
        //获取Hadoop默认配置
        Configuration configuration = new Configuration();
        configuration.set("fs:defaultFS","hdfs://master:8020");
        //获取FileSystem实例
        FileSystem fileSystem = FileSystem.get(configuration);
        //列出根目录下所有的文件和文件夹
        Path root = new Path("hdfs://master:8020/");
        FileStatus[] children = fileSystem.listStatus(root);
        for(FileStatus child : children){
            System.out.println(child.getPath().getName());
        }
        //创建文件
        Path newFile = new Path("hdfs://master:8020/tmp/new.txt");
        FSDataOutputStream outputStream
        = fileSystem.create(newFile);
        //将Hello World写入文件
        outputStream.writeUTF("Hello World");
        outputStream.close();
        //输出Hello World
        FSDataInputStream inputStream = fileSystem.open(newFile);
        String info = inputStream.readUTF();
        System.out.println(info);
        fileSystem.close();
    }
}

你可能感兴趣的:(Hadoop,HDFS,API)