import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.fs.FileSystem;
import java.io.*;
public class MoveFile {
public static boolean mv(Configuration conf, String remoteFilePath,
String remoteToFilePath) {
try (FileSystem fs = FileSystem.get(conf)) {
Path srcPath = new Path(remoteFilePath);
Path dstPath = new Path(remoteToFilePath);
return fs.rename(srcPath, dstPath);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 主函数
*/
public static void main(String[] args) {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://master:9000");
String remoteFilePath = "/user/hadoop/myLocalFile.txt"; // 源文件HDFS路径
String remoteToFilePath = "/user/hadoop/dir"; // 目的HDFS路径
try {
if (MoveFile.mv(conf, remoteFilePath, remoteToFilePath)) {
System.out.println("将文件 " + remoteFilePath + " 移动到 "
+ remoteToFilePath);
} else {
System.out.println("操作失败(源文件不存在或移动失败)");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
本文介绍了一种使用Java在Hadoop分布式文件系统(HDFS)中移动文件的方法。通过实例展示了如何利用Hadoop API实现远程文件的重命名及移动操作,并提供了完整的代码示例。
4215

被折叠的 条评论
为什么被折叠?



