
HDFS(Hadoop Distributed File System)是 Hadoop 生态系统中的分布式文件系统,用于存储大规模的数据。HDFS 的读写流程涉及多个组件,包括 NameNode、DataNode 和客户端。以下是详细的读写流程:
FileSystem API 发起写请求,请求创建一个新文件。FileSystem API 发起读请求,请求读取文件。示例代码
以下是一个简单的 Java 代码示例,展示了如何使用 Hadoop API 进行文件的读写操作:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
public class HdfsExample {
public static void main(String[] args) throws Exception {
// 配置 Hadoop
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://localhost:9000");
// 创建 FileSystem 对象
FileSystem fs = FileSystem.get(conf);
// 写文件
Path writePath = new Path("/user/test/write.txt");
FSDataOutputStream outputStream = fs.create(writePath);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write("Hello, HDFS!");
writer.close();
// 读文件
Path readPath = new Path("/user/test/write.txt");
FSDataInputStream inputStream = fs.open(readPath);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
// 关闭 FileSystem
fs.close();
}
}Configuration conf = new Configuration();:创建 Hadoop 配置对象。conf.set("fs.defaultFS", "hdfs://localhost:9000");:设置 HDFS 的地址。FileSystem fs = FileSystem.get(conf);:获取 HDFS 文件系统对象。Path writePath = new Path("/user/test/write.txt");:指定要写入的文件路径。FSDataOutputStream outputStream = fs.create(writePath);:创建输出流。BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));:创建缓冲写入器。writer.write("Hello, HDFS!");:写入数据。writer.close();:关闭写入器。Path readPath = new Path("/user/test/write.txt");:指定要读取的文件路径。FSDataInputStream inputStream = fs.open(readPath);:打开输入流。BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));:创建缓冲读取器。while ((line = reader.readLine()) != null) { System.out.println(line); }:逐行读取并输出数据。reader.close();:关闭读取器。fs.close();:关闭文件系统对象。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。