最终效果图
目录树实体类:
public class HdfsFolder {
private String id;
private String name;
private List<HdfsFolder> children;
set get 方法
}
定义所有方法共享常量:
// hdfs路径
private static String url = "hdfs://XXX:8020";
// 要读取的目录在hdfs下的相对路径
private static String USERFILEPATH = "/user/XXX";
初始化FileSystem对象
public static FileSystem getFileSystem() throws IOException, URISyntaxException {
Configuration conf = new Configuration();
conf.set("fs.hdfs.impl",org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
FileSystem fs = null;
if (org.apache.commons.lang.StringUtils.isBlank(url)) {
fs = FileSystem.get(conf);
} else {
URI uri = new URI(url.trim());
fs = FileSystem.get(uri, conf);
}
return fs;
}
根据路径递归读取 hdfs目录
public static void listFolderByCondition(String folder, HdfsFolder hdfsFolder) throws Exception{
FileSystem fs = HdfsUtils.getFileSystem();
FileStatus[] filesStatus = fs.listStatus(new Path(folder));
List<HdfsFolder> children = new ArrayList<>();
for (FileStatus file : filesStatus) {
if (file.isFile()){
HdfsFolder temp = new HdfsFolder();
temp.setId(folder + "/" + file.getPath().getName());
temp.setName(file.getPath().getName());
children.add(temp);
}
if (file.isDirectory()){
HdfsFolder temp = new HdfsFolder();
temp.setId(folder + "/" + file.getPath().getName());
temp.setName(file.getPath().getName());
listFolderByCondition(folder + "/" + file.getPath().getName(), temp);
children.add(temp);
}
}
hdfsFolder.setChildren(children);
}
public static HdfsFolder listFolder(String folder)
throws Exception {
FileSystem fs = HdfsUtils.getFileSystem();
FileStatus[] filesStatus = fs.listStatus(new Path(folder));
HdfsFolder hdfsFolder = new HdfsFolder();
hdfsFolder.setId(folder);
hdfsFolder.setName("根目录");
List<HdfsFolder> children = new ArrayList<>();
for (FileStatus file : filesStatus) {
if (file.isFile()){
HdfsFolder temp = new HdfsFolder();
temp.setId(folder + "/" + file.getPath().getName());
temp.setName(file.getPath().getName());
children.add(temp);
}
if (file.isDirectory()){
HdfsFolder temp = new HdfsFolder();
temp.setId(folder + "/" + file.getPath().getName());
temp.setName(file.getPath().getName());
listFolderByCondition(folder + "/" + file.getPath().getName(), temp);
children.add(temp);
}
}
hdfsFolder.setChildren(children);
return hdfsFolder;
}
根据文件全路径读取文件的内容
public static String checkFile(String fileName)
throws Exception {
FileSystem fs = getFileSystem();
FSDataInputStream inStream = fs.open(new Path(fileName));
BufferedReader br = new BufferedReader(new InputStreamReader(inStream, "UTf-8"));
StringBuffer buffer = new StringBuffer();
try {
String line;
line = br.readLine();
while (line != null) {
buffer.append(line).append("<br>");
line = br.readLine();
}
} finally {
br.close();
inStream.close();
}
return buffer.toString();
}