//类型枚举
public enum TYPE{
DIRECTORY,FILE,NOT_EXIST
}
//2.类型
public TYPE type(String path) throws IOException {
if (!exists(path)){
return TYPE.NOT_EXIST;
}
Path pt=new Path(path);
if (fileSystem.getFileStatus(pt).isFile()){
return TYPE.FILE;
}
return TYPE.DIRECTORY;
}
3.删除
//3.删除
public void deleteIfExist(String path) throws IOException {
Path ps = new Path(path);
switch (type(path)){
case FILE:
fileSystem.delete(ps,false);//不递归
break;
case DIRECTORY:
fileSystem.delete(ps,true);//递归
break;
}
}
4.创建目录
//4.创建目录
//针对目录,不存在则递归创建
public void mkdirIfNotExist(String path) throws IOException {
if (!exists(path)){
fileSystem.mkdirs(new Path(path));
}
}
5.上传
//5.将本地资源(文件 or 目录)【上传】到 HDFS上
//currDir:当前目录
//destDir:目标目录
public void uploadRecursive(File currDir,Path destDir,int currDepth,int maxDepth) throws IOException {
if (maxDepth<=0 && currDepth>maxDepth){
return;
}
for (File res : currDir.listFiles()) {
if (res.isDirectory()){
uploadRecursive(res,destDir,currDepth+1,maxDepth);
}else{
fileSystem.copyFromLocalFile(new Path(res.getPath()),destDir);
}
}
}
public void upload(String localPath,String dfsPath,boolean recursive,int...maxDepth) throws IOException {
//判断
File res = new File(localPath);//上传对象
if (!res.exists()){
throw new IOException("you can't upload the localPath that is not exist");
}
if (type(dfsPath)!= TYPE.DIRECTORY){
throw new IOException("you can't upload any resource to a file that it is directory");
}
Path local=new Path(localPath);
Path remote=new Path(dfsPath);
if (res.isFile()){
fileSystem.copyFromLocalFile(local,remote);
}else if (recursive){
int max = maxDepth[0];
max = max<0?0:max;
uploadRecursive(res,remote,1,max);
}else {
throw new IOException("you can't upload a directory when parameter recursive was set false");
}
}
6.下载
//6.从HDFS上【下载】至本地
public void download(String dfsPath,String localDir) throws IOException {
//判断
if (exists(dfsPath)){
File local;
if ((local=new File(localDir)).exists()){
Path remote = new Path(dfsPath);
Path localPath = new Path(localDir);
fileSystem.copyToLocalFile(remote,localPath);
}else {
throw new IOException("you can't download a resource to local file");
}
}else {
throw new IOException("you can't download a remote resource that is not exist");
}
}