복붙노트

[HADOOP] JAVA API를 사용하여 HDFS에서 파일을 이동하거나 복사하는 방법

HADOOP

JAVA API를 사용하여 HDFS에서 파일을 이동하거나 복사하는 방법

HDFS : // abc : 9000 / user / a.txt에서 HDFS : // abc : 9000 / user / 123 /로 파일을 복사하는 것과 같은 파일을 동일한 HDFS에 복사하고 싶습니다.

JAVA API를 사용하여이를 수행 할 수 있습니까? 감사

해결법

  1. ==============================

    1.FileUtil은 파일 복사 방법을 제공합니다.

    FileUtil은 파일 복사 방법을 제공합니다.

    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);
    

    다른 클러스터에 복사해야하는 경우 새 구성 및 설정과 새 FileSystem을 만드십시오.

  2. ==============================

    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 !!")
        }
    
  3. from https://stackoverflow.com/questions/38141516/how-to-move-or-copy-file-in-hdfs-by-using-java-api by cc-by-sa and MIT license