java操作hdfs:

 

public static void deletedir(FileSystem fs,String dir)
{
Path hadooppath = new Path(dir);
try {
if (!fs.exists(hadooppath)){
System.out.println("目录不存在!");
}else{
FileStatus[] filelist = fs.listStatus(new Path(dir));
if(filelist.length==0)
{
fs.delete(hadooppath,true);
}else{
System.out.println("目录非空,是否删除:1、是 2、否");
int a=cin.nextInt();
if(a==1) fs.delete(hadooppath,true);
}
}
} catch (IOException e) {
e.printStackTrace();
}

}
public static void addtext(FileSystem fs, String hadooppath) {
Path remotePath = new Path(hadooppath);
FSDataInputStream in = null;
try {
if(fs.exists(remotePath)) {
in = fs.open(remotePath);
BufferedReader d = new BufferedReader(new InputStreamReader(in));
String line = null;
System.out.println("文件内容:");
String text="";
String addtext="";
while ((line = d.readLine()) != null) {
String[] strarray = line.split(" ");
for (int i = 0; i < strarray.length; i++) {
text+=strarray[i];
System.out.print(strarray[i]);
System.out.print(" ");
}
System.out.println(" ");
}
System.out.println("输入追加内容:");
addtext=cin.next();
int temp=0;
System.out.println("追加到原有文件的开头或结尾:1、开头 2、末尾");
temp=cin.nextInt();
if(temp==1)
{
text=addtext+text;
}else{
text+=addtext;
}
FSDataOutputStream os = fs.create(remotePath);
os.writeUTF(text);
os.close();
d.close();
}else{
System.out.println("文件不存在!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void movefile(FileSystem fs,String path,String newPath)
{
try {
if (fs.exists(new Path(newPath))&&fs.exists(new Path(path))){
fs.rename(new Path(path),new Path(newPath));
}else {
System.out.println("路径错误!");
}
} catch (Exception e) {

} finally {
//close(fs);
}
}

 

posted on 2021-10-11 15:42  sean1246  阅读(21)  评论(0编辑  收藏  举报