eclipse下使用API操作HDFS

1)使用eclipse,在HDFS上创建新目录

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class test01{
public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();   
FileSystem hdfs =FileSystem.get(conf); Path findf=new Path("/eclipse-test4"); /*boolean isExists=hdfs.exists(findf); System.out.println("/user/output exit?"+isExists); if(isExists) { hdfs.delete(findf, true); System.out.println("delete /user/output"); } */ hdfs.mkdirs(findf); System.out.println("over"); } }

run上述java代码之后,使用hdfs shell查看,结果并未发现生成新目录,但是将上述java代码打包成jar包之后,使用hadoop jar命令却可以成功在HDFS上创建新目录。在上述代码的基础上增加三行代码如下:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class test01{
public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();   
    //
    conf.set("fs.default.name", "hdfs://Master:9000/");  
    conf.set("hadoop.job.user","hadoop");    
    //指定jobtracker的ip和端口号,master在/etc/hosts中可以配置  
    conf.set("mapred.job.tracker","Master:9001");  
    FileSystem hdfs =FileSystem.get(conf);
    Path findf=new Path("/eclipse-test4");
    /*boolean isExists=hdfs.exists(findf);
    System.out.println("/user/output exit?"+isExists);
    if(isExists)
    {
        hdfs.delete(findf, true);
        System.out.println("delete /user/output");
        
    }
    */
    hdfs.mkdirs(findf);
    System.out.println("over");
}
}

可以成功在hdfs上创建新目录了。

原文地址:https://www.cnblogs.com/lz3018/p/4896249.html