HDFS Java API 介绍
·
以下是 HDFS Java API 6 大类核心功能的独立代码示例,每个功能单独成类,可直接复制运行(需确保 Hadoop 依赖已配置,且集群正常运行,注意修改代码中hdfs地址)
1. 连接管理 API(获取 / 关闭 HDFS 连接)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import java.net.URI;
public class HDFSConnectionDemo {
public static void main(String[] args) throws Exception {
// 1. 配置HDFS连接信息
Configuration conf = new Configuration();
String hdfsUri = "hdfs://192.168.131.140:8020"; // 替换为你的HDFS地址
String user = "root"; // 替换为你的Hadoop用户名
// 2. 获取FileSystem实例(核心连接方法)
FileSystem fs = FileSystem.get(new URI(hdfsUri), conf, user);
System.out.println("HDFS连接成功!FileSystem实例:" + fs);
// 3. 关闭连接(必须执行,释放资源)
fs.close();
System.out.println("HDFS连接已关闭");
}
}
2. 目录操作 API(创建 / 删除 / 列出 / 重命名目录)
2.1 创建目录(支持多级)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSMkdirDemo {
public static void main(String[] args) throws Exception {
// 初始化连接
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 创建多级目录
Path dirPath = new Path("/api-test/dir1/subdir");
boolean isCreated = fs.mkdirs(dirPath); // 递归创建所有不存在的父目录
if (isCreated) {
System.out.println("目录创建成功:" + dirPath);
} else {
System.out.println("目录已存在或创建失败:" + dirPath);
}
fs.close();
}
}
2.2 删除目录(支持递归删除非空目录)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSDeleteDirDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 删除目录(第二个参数true=递归删除,false=仅删除空目录)
Path dirPath = new Path("/api-test-renamed");
boolean isDeleted = fs.delete(dirPath, true);
if (isDeleted) {
System.out.println("目录删除成功:" + dirPath);
} else {
System.out.println("目录不存在或删除失败:" + dirPath);
}
fs.close();
}
}
2.3 列出目录内容(含文件 / 子目录信息)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import java.net.URI;
public class HDFSListDirDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 列出目录内容(第二个参数true=递归列出所有子目录,false=仅当前目录)
Path dirPath = new Path("/");
RemoteIterator<LocatedFileStatus> fileIter = fs.listFiles(dirPath, false);
System.out.println("目录 " + dirPath + " 的内容:");
while (fileIter.hasNext()) {
LocatedFileStatus fileStatus = fileIter.next();
Path path = fileStatus.getPath();
String type = fileStatus.isDirectory() ? "目录" : "文件";
long size = fileStatus.getLen(); // 文件大小(目录为0)
System.out.println(type + ":" + path + ",大小:" + size + "B");
}
fs.close();
}
}
2.4 重命名目录
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSRenameDirDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 原目录路径 + 新目录路径
Path oldPath = new Path("/api-test");
Path newPath = new Path("/api-test-renamed");
boolean isRenamed = fs.rename(oldPath, newPath);
if (isRenamed) {
System.out.println("目录重命名成功:" + oldPath + " → " + newPath);
} else {
System.out.println("目录不存在或重命名失败");
}
fs.close();
}
}
3. 文件操作 API(上传 / 下载 / 删除 / 重命名 / 检查存在)
3.1 本地文件上传到 HDFS
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSUploadFileDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 本地文件路径(绝对路径)+ HDFS目标路径
Path localPath = new Path("C:/Users/ASUS/Desktop/1.txt");
Path hdfsPath = new Path("/api-test/uploaded-file.txt");
// 上传文件(自动覆盖已存在文件)
fs.copyFromLocalFile(localPath, hdfsPath);
System.out.println("文件上传成功:" + localPath + " → " + hdfsPath);
fs.close();
}
}
3.2 HDFS 文件下载到本地
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSDownloadFileDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// HDFS文件路径 + 本地目标路径
Path hdfsPath = new Path("/api-test/uploaded-file.txt");
Path localPath = new Path("C:/Users/ASUS/Desktop/downloaded-file.txt"); // 本地保存路径
// 下载文件(若本地文件已存在,会覆盖)
fs.copyToLocalFile(hdfsPath, localPath);
System.out.println("文件下载成功:" + hdfsPath + " → " + localPath);
fs.close();
}
}
3.3 删除 HDFS 文件
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSDeleteFileDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 要删除的文件路径
Path filePath = new Path("/api-test/uploaded-file.txt");
boolean isDeleted = fs.delete(filePath, false); // 第二个参数false=删除文件(true用于目录)
if (isDeleted) {
System.out.println("文件删除成功:" + filePath);
} else {
System.out.println("文件不存在或删除失败:" + filePath);
}
fs.close();
}
}
3.4 重命名 HDFS 文件
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSRenameFileDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 原文件路径 + 新文件路径
Path oldPath = new Path("/api-test/uploaded-file.txt");
Path newPath = new Path("/api-test/renamed-file.txt");
boolean isRenamed = fs.rename(oldPath, newPath);
if (isRenamed) {
System.out.println("文件重命名成功:" + oldPath + " → " + newPath);
} else {
System.out.println("文件不存在或重命名失败");
}
fs.close();
}
}
3.5 检查 HDFS 文件是否存在
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSFileExistsDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 要检查的文件路径
Path filePath = new Path("/api-test/renamed-file.txt");
boolean exists = fs.exists(filePath);
if (exists) {
System.out.println("文件存在:" + filePath);
} else {
System.out.println("文件不存在:" + filePath);
}
fs.close();
}
}
4. 内容读写 API(读取 / 写入 / 追加文件内容)
4.1 读取 HDFS 文件内容
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Path;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
public class HDFSReadFileDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 要读取的文件路径
Path filePath = new Path("/api-test/write-test.txt");
FSDataInputStream in = fs.open(filePath); // 获取输入流
// 缓冲读取文件内容
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line;
System.out.println("文件内容:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 关闭流
reader.close();
fs.close();
}
}
4.2 写入内容到 HDFS 文件(新建文件)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import java.net.URI;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class HDFSWriteFileDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
Path filePath = new Path("/api-test/write-test.txt");
FSDataOutputStream out = fs.create(filePath);
// 关键:用OutputStreamWriter指定编码(UTF-8),再用BufferedWriter写入字符串
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
String content = "Hello HDFS! 这是通过Java API写入的内容\n第二行内容";
writer.write(content); // 用字符流写入,保证编码正确
writer.close();
out.close();
fs.close();
System.out.println("内容写入成功:" + filePath);
}
}
4.3 追加内容到 HDFS 文件(需开启追加配置)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.URI;
public class HDFSAppendFileDemo {
public static void main(String[] args) throws Exception {
// 开启HDFS追加支持(默认关闭)
Configuration conf = new Configuration();
conf.set("dfs.support.append", "true");
conf.set("dfs.client.block.write.replace-datanode-on-failure.policy", "NEVER");
// 额外建议添加:指定HDFS namenode地址(避免配置文件缺失导致的连接问题)
conf.set("fs.defaultFS", "hdfs://192.168.131.140:8020");
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 要追加的文件路径(必须已存在)
Path filePath = new Path("/api-test/write-test.txt");
FSDataOutputStream out = fs.append(filePath); // 获取追加流
// 关键:用OutputStreamWriter指定编码(与写入时保持一致,如UTF-8)
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
String appendContent = "\n这是追加的内容(通过append方法)";
writer.write(appendContent); // 用字符流写入,保证中文编码正确
// 关闭流(先关writer,再关out)
writer.close();
out.close();
fs.close();
System.out.println("内容追加成功:" + filePath);
}
}
5. 元数据与状态 API(获取文件 / 目录元数据、块信息)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.net.URI;
import java.util.Arrays;
public class HDFSMetadataDemo {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.131.140:8020"), conf, "root");
// 目标文件路径
Path filePath = new Path("/api-test/write-test.txt");
FileStatus fileStatus = fs.getFileStatus(filePath); // 获取元数据
// 打印元数据信息
System.out.println("=== 文件元数据 ===");
System.out.println("路径:" + fileStatus.getPath());
System.out.println("类型:" + (fileStatus.isDirectory() ? "目录" : "文件"));
System.out.println("大小:" + fileStatus.getLen() + "B");
System.out.println("权限:" + fileStatus.getPermission());
System.out.println("所有者:" + fileStatus.getOwner());
System.out.println("修改时间:" + fileStatus.getModificationTime());
// 获取文件块信息(仅文件有效)
if (!fileStatus.isDirectory()) {
BlockLocation[] blocks = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
System.out.println("\n=== 文件块信息 ===");
for (int i = 0; i < blocks.length; i++) {
System.out.println("块 " + (i+1) + ":");
System.out.println(" 存储节点:" + Arrays.toString(blocks[i].getHosts()));
System.out.println(" 块大小:" + blocks[i].getLength() + "B");
}
}
fs.close();
}
}
6. 权限管理 API(设置文件 / 目录权限)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.permission.FsPermission; // 修正包路径
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import java.net.URI;
public class HDFSPermissionDemo {
public static void main(String[] args) throws Exception {
// 1. 配置HDFS连接信息
Configuration conf = new Configuration();
String hdfsUri = "hdfs://192.168.131.140:8020";
String user = "root";
FileSystem fs = FileSystem.get(new URI(hdfsUri), conf, user);
// 2. 目标路径(确保存在)
Path targetPath = new Path("/api-test/write-test.txt");
// 3. 检查路径是否存在
if (!fs.exists(targetPath)) {
System.out.println("目标路径不存在:" + targetPath);
fs.close();
return;
}
// 4. 设置权限(两种方式选其一)
// 方式1:字符串格式(如755)
FsPermission permission = new FsPermission("755");
fs.setPermission(targetPath, permission);
// 方式2:八进制数字(与Linux一致)
// FsPermission permission = new FsPermission((short) 0755);
// 5. 验证并输出权限
FileStatus status = fs.getFileStatus(targetPath);
FsPermission setPermission = status.getPermission();
String pathType = status.isDirectory() ? "目录" : "文件";
System.out.println("=== 权限设置完成 ===");
System.out.println("目标" + pathType + ":" + targetPath);
System.out.println("设置的权限:755(rwxr-xr-x)");
System.out.println("实际生效权限:" + setPermission.toString());
// 6. 解析权限字符串
String permStr = setPermission.toString();
System.out.println("\n权限解析:");
System.out.println("所有者权限:" + permStr.substring(0, 3));
System.out.println("组用户权限:" + permStr.substring(3, 6));
System.out.println("其他用户权限:" + permStr.substring(6, 9));
// 7. 关闭连接
fs.close();
}
}
更多推荐

所有评论(0)