Hadoop从绝对路径和基本路径获取相对路径

Ven*_*k K 2 java hadoop mapreduce

给定绝对基本路径,我想从绝对路径获取相对路径。是否有任何 Hadoop Java API 可以做到这一点?

例如,如果我的绝对 HDFS 路径是abs_path = hdfs://name-node/level1/level2/level3并且我的绝对基本路径是abs_base_path = hdfs://name-node/level1,我想从 中提取相对路径abs_path,即rel_path = level2/level3. 我熟悉使用路径构造函数来组合两个路径。

例如,如果我有rel_pathand abs_base_path,我可以使用 Path 类中重载的构造函数之一http://hadoop.apache.org/docs/current/api/org/apache/hadoop/fs/Path来构建,abs_path但我找不到 API 来执行相反的操作。

lau*_*man 5

这实际上是在FileOutputCommitter的源代码中完成的。相关函数是

   /**
   * Find the final name of a given output file, given the job output directory
   * and the work directory.
   * @param jobOutputDir the job's output directory
   * @param taskOutput the specific task output file
   * @param taskOutputPath the job's work directory
   * @return the final path for the specific output file
   * @throws IOException
   */
  private Path getFinalPath(Path jobOutputDir, Path taskOutput, 
                            Path taskOutputPath) throws IOException {
    URI taskOutputUri = taskOutput.toUri();
    URI relativePath = taskOutputPath.toUri().relativize(taskOutputUri);
    if (taskOutputUri == relativePath) {
      throw new IOException("Can not get the relative path: base = " + 
          taskOutputPath + " child = " + taskOutput);
    }
    if (relativePath.getPath().length() > 0) {
      return new Path(jobOutputDir, relativePath.getPath());
    } else {
      return jobOutputDir;
    }
  }
Run Code Online (Sandbox Code Playgroud)

这个想法是为基本目录创建一个 URI,然后为这个新的、相对化的 URI 创建一个新的路径。

希望有帮助。