/**
* 从hdfs上下载单个文件
* @param fileSystemPath hdfs上文件路径,具体到文件名称
* @param filePath 文件保存路径 具体到文件名称
*/
public static void downloadSingleFile(String fileSystemPath,String filePath) throws IOException {
//1 创建连接
Configuration conf = new Configuration();
//2 连接端口
conf.set("fs.defaultFS", "hdfs://hcluster");
FileSystem fileSystem = FileSystem.get(conf);
FSDataInputStream in = fileSystem.open(new Path(fileSystemPath));//获取服务器文件
FileOutputStream out = new FileOutputStream(new File(filePath));//选择下载路径,下载文件名
IOUtils.copyBytes(in,out,conf);
in.close();
out.close();
}
/**
* 从hdfs上下载整个文件夹
* @param fileSystemPath hdfs上文件路径
* @param filePath 文件保存路径
*/
public static void downloadFolder(String fileSystemPath,String filePath) throws IOException {
//1 创建连接
Configuration conf = new Configuration();
//2 连接端口
conf.set("fs.defaultFS", "hdfs://hcluster");
FileSystem fileSystem = FileSystem.get(conf);
FileStatus[] listStatus = fileSystem.listStatus(new Path(fileSystemPath));//获取文件列表
for (FileStatus fileStatus : listStatus) {
isDir(fileStatus, fileSystem,filePath,fileSystemPath);//遍历文件列表,判断是文件还是文件夹
}
}
/**
* 判断hdfs是不是文件夹
* @param fileStatus hdfs文件信息
* @param fileSystem hdfs配置信息
* @param localDirPath 保存在本地的文件夹路径
* @param fileSystemPath 从hdfs某个文件夹下拉取所有文件的文件夹路径
* @throws IOException
*/
public static void isDir(FileStatus fileStatus, FileSystem fileSystem,String localDirPath,String fileSystemPath) throws IOException {
//如果是文件夹,则获取该文件夹下的文件列表,遍历判断 递归调用
if(fileStatus.isDirectory()) {//如果是文件夹,则在本地创建这个文件夹
FileStatus[] listStatus;
String replace = fileStatus.getPath().toString().replace(fileSystem.getUri().toString(), "");
try {
listStatus = fileSystem.listStatus(new Path(replace));
File fileDir = new File(localDirPath + replace);
if(!fileDir.exists()){
fileDir.mkdirs();
}
for (FileStatus fileStatus2 : listStatus) {
isDir(fileStatus2,fileSystem,localDirPath,fileSystemPath);
}
} catch (Exception e) {
e.printStackTrace();
}
}else {
String replace = fileStatus.getPath().toString().replace(fileSystem.getUri().toString(), "");
FSDataInputStream in = fileSystem.open(new Path(replace));//获取服务器文件
File dir = new File(localDirPath + fileSystemPath);
if(!dir.exists()){
dir.mkdirs();
}
FileOutputStream out = new FileOutputStream(new File(localDirPath + replace));//选择下载路径,下载文件名
byte[] b = new byte[1024];
int len = 0;
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
in.close();
out.close();
}
}