在深入 HDFS 数据读写之前,先理清几个核心类。FileSystem 是通用文件系统的抽象基类,所有操作 Hadoop 文件系统的代码都依赖它。在 HDFS 中,DistributedFileSystem 是其具体实现。FileSystem.open() 返回 FSDataInputStream,对应 HDFS 的 DFSInputStream;create() 返回 FSDataOutputStream,对应 DFSOutputStream。
一、读数据的过程
客户端调用 open() 打开文件时,DistributedFileSystem 会创建 DFSInputStream。构造函数中,输入流通过 ClientProtocol.getBlockLocations() 远程调用名称节点,获取文件起始数据块的位置信息。名称节点返回保存该块的所有数据节点地址,并按距离客户端远近排序。随后,DistributedFileSystem 实例化 FSDataInputStream 返回给客户端。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class Chapter3 {
public static void main(String[] args) {
try {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://localhost:9000");
conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
FileSystem fs = FileSystem.get(conf);
Path file = new Path("test");
FSDataInputStream getIt = fs.open(file);
BufferedReader ( (getIt));
d.readLine();
System.out.println(content);
d.close();
fs.close();
} (Exception e) {
e.printStackTrace();
}
}
}


