如何获取目录中文件的绝对路径?

问题描述:

我有一个包含文件,目录,子目录等的目录。如何使用Apache Hadoop API获取所有文件和目录的绝对路径列表?如何获取目录中文件的绝对路径?

使用HDFS API:

package org.myorg.hdfsdemo; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

import org.apache.hadoop.conf.Configuration; 
import org.apache.hadoop.fs.FileStatus; 
import org.apache.hadoop.fs.FileSystem; 
import org.apache.hadoop.fs.Path; 



public class HdfsDemo { 

    public static void main(String[] args) throws IOException { 

     Configuration conf = new Configuration(); 
     conf.addResource(new Path("/Users/miqbal1/hadoop-eco/hadoop-1.1.2/conf/core-site.xml")); 
     conf.addResource(new Path("/Users/miqbal1/hadoop-eco/hadoop-1.1.2/conf/hdfs-site.xml")); 
     FileSystem fs = FileSystem.get(conf); 
     System.out.println("Enter the directory name :"); 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     Path path = new Path(br.readLine()); 
     displayDirectoryContents(fs, path); 
    } 

    private static void displayDirectoryContents(FileSystem fs, Path rootDir) { 
     // TODO Auto-generated method stub 
     try { 

      FileStatus[] status = fs.listStatus(rootDir); 
      for (FileStatus file : status) { 
       if (file.isDir()) { 
        System.out.println("This is a directory:" + file.getPath()); 
        displayDirectoryContents(fs, file.getPath()); 
       } else { 
        System.out.println("This is a file:" + file.getPath()); 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+3

@Peter Shipilo:一个小小的更正,不要忘记关闭FileSystem实例。 – Tariq

+0

谢谢你差异很大。我将在稍后尝试此代码。 –

+0

而且您需要hadoop-hdfs等的正确依赖关系。 – Mahdi

编写一个递归函数,它接受一个文件并检查它是否是一个目录,如果目录列出它中的所有文件并在for循环中检查该文件是否为目录,然后递归调用或仅返回文件。

事情是这样的,但下面不完全相同(这里我只返回.java文件)

private static List<File> recursiveDir(File file) { 
    if (!file.isDirectory()) { 
//   System.out.println("[" + file.getName() + "] is not a valid directory"); 
     return null; 
    } 

    List<File> returnList = new ArrayList<File>(); 
    File[] files = file.listFiles(); 
    for (File f : files) { 
     if (!f.isDirectory()) { 
      if (f.getName().endsWith("java")) { 
       returnList.add(f); 
      } 
     } else { 
      returnList.addAll(recursiveDir(f)); 
     } 
    } 
    return returnList; 
} 
+0

谢谢,但我在寻找如何使用Apache Hadoop的做到这一点。 但现在我知道解决方案。 –

与HDFS可以使用Hadoop的FS -lsr。

+0

或'hdfs dfs ls -R' - 但它不会给我们绝对路径,是吗? –

+0

问题是关于API,而不是CLI客户端。 –