How to move or copy file in HDFS by using JAVA API

孤街浪徒 提交于 2019-12-29 07:13:46

问题


I want to copy file in THE SAME HDFS ,just like copy file from HDFS://abc:9000/user/a.txt to HDFS://abc:9000/user/123/

Can I do that by using JAVA API? Thanks


回答1:


FileUtil provides a method for copying files.

Configuration configuration = new Configuration();
configuration.set("fs.defaultFS", "hdfs://abc:9000");
FileSystem filesystem = FileSystem.get(configuration);
FileUtil.copy(filesystem, new Path("src/path"), filesystem, new Path("dst/path"), false, configuration);

If you need to copy it to another cluster, just make a new Configuration and setup and new FileSystem.




回答2:


If you want to move files from directory it is little bit tricky below code done same task for me !!
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://sourcePath/")
    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 !!")
    }


来源:https://stackoverflow.com/questions/38141516/how-to-move-or-copy-file-in-hdfs-by-using-java-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!