HDFS JAVA API操作

一、 读文件
操作步骤:
1.连接HDFS系统

Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://hadoop.skedu.com:9000");

2.获得文件系统

FileSystem fileSystem = FileSystem.get(configuration);

3.指定文件路径对象

String filePath = "/user/root/mapreduce/wordcount/input/my.input"
Path readPath = new Path(filePath);

4.获得输入流对象

//open()方法为打开文件流
FSDataInputStream inputStream = fileSystem.open(readPath);

5.输出文件信息

try{
   IOUtils.copyBytes(inputStream,System.out,4096,false);
}catch (Exception e){
   e.printStackTrace();
}finally {
   IOUtils.closeStream(inputStream);
}

这里写图片描述

结果如下:
这里写图片描述


二、 写文件
在进行写操作的时候,涉及到写权限Hadoop的HDFS会进行安全检测,为了避免 没有写权限而失败,我们暂时将它关闭。
配置 etc/hadoop/hdfs-site.xml文件:

    <property>
        <name>dfs.permissions</name>
        <value>false</value>
     </property>

操作步骤:
1.连接HDFS系统

Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://hadoop.skedu.com:9000");

2.获得文件系统对象

FileSystem fileSystem = FileSystem.get(configuration);

3.准备本地文件

String localFilePath =
HdfsDemo.class.getClassLoader().getResource("my.log").getPath();
FileInputStream inputStream = new FileInputStream(new File(localFilePath));

4.准备Put文件路径

String hdfsDirPath = "/user/root/mapreduce/wordcount/wcinput/my.log";
Path path = new Path(hdfsDirPath);

5.获得输入流对象

FSDataOutputStream outputStream = fileSystem.create(path);

6.put写入

try{
   IOUtils.copyBytes(inputStream,outputStream,4096,false);
}catch (Exception e){
   e.printStackTrace();
}finally {
   IOUtils.closeStream(inputStream);
   IOUtils.closeStream(outputStream);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值