import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
//查找某个文件在HDFS集群中的位置
public class FindFile {
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
FileSystem fileSystem = FileSystem.get(conf);
// 必须是一个具体的文件
Path path = new Path("/usr/demo.txt");
// 文件状态
FileStatus fileStatus = fileSystem.getFileStatus(path);
// 文件块
BlockLocation[] blockLocations = fileSystem.getFileBlockLocations(
fileStatus, 0, fileStatus.getLen());
int blockLen = blockLocations.length;
System.err.println("block Count:" + blockLen);
for (int i = 0; i < blockLen; i++) {
//主机名
String[] hosts = blockLocations[i].getHosts();
for(String s:hosts){
System.err.println(s);
}
}
}
}
Console:
block Count:1
huangpeng-K53SD