2011-03-31 20 views
14

我想使用Java API在HDFS中移動文件。我無法想出辦法做到這一點。 FileSystem類似乎只想允許移入和移出本地文件系統......但我想將它們保存在HDFS中並將它們移動到那裏。使用Java API在Hadoop中移動文件?

我缺少一些基本的東西嗎?我唯一能做的就是從輸入流中讀取它並將其寫回...然後刪除舊副本(yuck)。

感謝

回答

17

使用FileSystem.rename()

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

Renames Path src to Path dst . Can take place on local fs or remote DFS.

Parameters:
src - path to be renamed
dst - new path after rename
Returns:
true if rename is successful
Throws:
IOException - on failure

+0

黨......我怎麼會錯過呢?謝謝!!! – Wanderer 2011-04-01 11:31:31

+1

'FileSystem.rename()'是一種抽象方法。那麼這將如何工作? – zeekvfu 2014-07-29 09:46:55

+0

您必須獲得與正在使用的文件系統(例如HDFS)相對應的FileSystem實現。 'FileSystem fs = myPath.getFileSystem(config); fs.rename(myPath,otherPath);' – 2015-10-22 14:16:59

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 !!") 
     } 
3

的是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) 
+0

有趣的外觀方便移動文件 – Nitin 2017-10-25 18:53:58