hadoop 学习(四)之java操作hdfs

1、导入hadoop jar包

将hadoop/share/common/目录、hadoop/share/common/lib/目录、hadoop/hdfs/目录、下的jar包加入eclipse。

2、开始编码调用

static FileSystem  fs=null;
    public static  void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        init();        
        testUpload();
    }
    
    
    public static void init() throws Exception{
        fs=FileSystem.get(new URI("hdfs://192.168.1.7:9000"), new  Configuration(),"hadoop");
        
    }
    
    /**
     * 将本地文件复制到hdfs文件系统里面
     * @throws Exception
     * @throws IOException
     */

    public static void testUpload() throws Exception, IOException{
        OutputStream remote= fs.create(new Path("/uploadjdk"));
        FileInputStream local=new FileInputStream("c://jdk.rar");
        IOUtils.copyBytes(local, remote,4096,true);
    }
    
    /**
     * 从hdfs文件系统里面下载文件 
     * @throws Exception
     * @throws IOException
     */
    
    public void testDownload() throws Exception, IOException{
        InputStream in= fs.open(new Path("/eclipse-SDK-4.3.1-linux-gtk-x86_64.tar.gz"));
        OutputStream output=new FileOutputStream("c://jdk2.rar");
        IOUtils.copyBytes(in, output,4096,true);
    }

testUpload 方法是将本地“c://jdk.rar”文件上传到hdfs系统根目录中并命名为uploadjdk.

testDownload 方法是将hdfs系统中的根目录下的“eclipse-SDK-4.3.1-linux-gtk-x86_64.tar.gz”下载到本址c盘,并命名为“jdk2.rar”
值得注意的是:hdfs://192.168.1.7:9000"地址是第二篇文章“ubuntu hadoop 2.7.0 伪分部安装”中   /usr/local/hadoop/etc/hadoop/core-site.xml 文件中配置的地址。如果配置的为

"hdfs://localhost:9000" 需要将其更改为实际机器IP才可以正常访问。

原文地址:https://www.cnblogs.com/lvlv/p/4496299.html