获取hadoop文件系统的5种方式

本文介绍了通过Java操作Hadoop文件系统(HDFS)的五种方法,包括使用URL、FileSystem类及其不同构造函数。代码示例展示了如何连接到HDFS节点并读取文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.cn.demo01;

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;
import org.junit.Test;

import java.io.*;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;


public class HdfsOperate {
    //通过URL来获取,不常用了解
    @Test
    public void downHdfsFiles() throws IOException {
        //注册一个驱动,访问hdfs文件系统
        URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
        String url = "hdfs://node01:8020/profile";
        InputStream inputStream = new URL(url).openStream();
        OutputStream outputStream = new FileOutputStream(new File("D:\\hello.txt"));
        IOUtils.copy(inputStream, outputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }

    //通过FileSystem类来获取,了解源码   不加参数默认本地文件系统的原因
    @Test
    public void getFilesystem() throws Exception {
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://node01:8020");
        FileSystem fileSystem = FileSystem.get(configuration);
        System.out.println(fileSystem.toString());
        fileSystem.close();
    }

    @Test
    public void  getFilesystem2() throws URISyntaxException, IOException {
        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"),configuration);
        System.out.println(fileSystem.toString());
        fileSystem.close();

    }

    @Test
    public  void getFilesystem3() throws IOException {
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://node01:8020");
        FileSystem fileSystem = FileSystem.newInstance(configuration);
        System.out.println(fileSystem.toString());
        fileSystem.close();
    }

    @Test
    public  void getFilesystem4() throws IOException, URISyntaxException {
        Configuration configuration = new Configuration();
        FileSystem fileSystem = FileSystem.newInstance(new URI("hdfs://node01:8020"),configuration);
        System.out.println(fileSystem.toString());
        fileSystem.close();
    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值