我想使用 Java API 在 HDFS 中移动文件。我想不出办法来做到这一点。FileSystem 类似乎只允许进出本地文件系统。但我想将它们保存在 HDFS 中并将它们移到那里。
我错过了一些基本的东西吗?我能想到的唯一方法是从输入流中读取它并将其写回......然后删除旧副本(糟糕)。
谢谢
public abstract boolean rename(Path src, Path dst) throws IOException
将 Path重命名
src
为 Pathdst
。可以在本地 fs 或远程 DFS 上进行。参数:
src
- 要重命名的
dst
路径 - 重命名后的新路径
返回:
true
如果重命名成功
抛出:
IOException - 失败
java.nio.* 方法可能并不总是适用于 HDFS。所以找到了以下有效的解决方案。
使用 org.apache.hadoop.fs.FileUtil.copy API 将文件从一个目录移动到另一个目录
val fs = FileSystem.get(new Configuration())
val conf = new org.apache.hadoop.conf.Configuration()
val srcFs = FileSystem.get(new org.apache.hadoop.conf.Configuration())
val dstFs = FileSystem.get(new org.apache.hadoop.conf.Configuration())
val dstPath = new org.apache.hadoop.fs.Path(DEST_FILE_DIR)
for (file <- fileList) {
// The 5th parameter indicates whether source should be deleted or not
FileUtil.copy(srcFs, file, dstFs, dstPath, true, conf)
我认为 FileUtilts replaceFile 也可以解决这个目的。 http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/fs/FileUtil.html#replaceFile(java.io.File , java.io.File)
hdfsDirectory="hdfs://srcPath"
val conf = new org.apache.hadoop.conf.Configuration()
val src:Path = new org.apache.hadoop.fs.Path(hdfsDirectory)
val fs = FileSystem.get(src.toUri,conf)
val srcPath: Path = new Path("hdfs://srcPath")
val srcFs =FileSystem.get(srcPath.toUri,conf)
val dstPath:Path =new Path("hdfs://targetPath/")
val dstFs =FileSystem.get(dstPath.toUri,conf)
val exists = fs.exists(new org.apache.hadoop.fs.Path(hdfsDirectory))
val status:Array[FileStatus] = fs.listStatus(new Path(hdfsDirectory))
if (status.length>0) {
status.foreach(x => {
println("My files: " + x.getPath)
FileUtil.copy(srcFs, x.getPath, dstFs, dstPath, true, conf)
println("Files moved !!" +x.getPath)
}
)}
else{
println("No Files Found !!")
}