17

我想使用 Java API 在 HDFS 中移动文件。我想不出办法来做到这一点。FileSystem 类似乎只允许进出本地文件系统。但我想将它们保存在 HDFS 中并将它们移到那里。

我错过了一些基本的东西吗?我能想到的唯一方法是从输入流中读取它并将其写回......然后删除旧副本(糟糕)。

谢谢

4

4 回答 4

24

使用FileSystem.rename()

public abstract boolean rename(Path src, Path dst) throws IOException

将 Path重命名src为 Path dst。可以在本地 fs 或远程 DFS 上进行。

参数:
src - 要重命名的
dst路径 - 重命名后的新路径
返回:
true如果重命名成功
抛出:
IOException - 失败

于 2011-04-01T00:47:01.207 回答
5

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)
于 2017-09-21T18:24:39.860 回答
1

我认为 FileUtilts replaceFile 也可以解决这个目的。 http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/fs/FileUtil.html#replaceFile(java.io.File , java.io.File)

于 2011-06-28T23:47:12.513 回答
0
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 !!")
        }
于 2017-01-10T08:48:55.683 回答