hadoop深入浅出-JAVA操作HDFS(JAVA接口使用)

package sunyuqiang.com;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class App 
{
    public static void main( String[] args ) throws IOException {

        testGet();//测试读取
        System.out.println("_____________________________");
        testPut();//测试写入
    }
    public static void testGet() throws IOException
    {
        //连接HDFS系统
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://sunyuqiang.com:9000");
        //获得文件系统对象
        FileSystem fileSystem = FileSystem.get(configuration);
        //指定文件路径对象
        String filePath = "/user/hadoop/mapreduce/wordcount/input/my.txt";
        Path readPath = new Path(filePath);
        //open()文件流,获得输入流对象
        FSDataInputStream inputStream = fileSystem.open(readPath);
        //输出文件信息
        try{
            IOUtils.copyBytes(inputStream,System.out,4096,false);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            IOUtils.closeStream(inputStream);
        }
    }
    public static void testPut() throws IOException
    {
        //连接HDFS系统
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS","hdfs://sunyuqiang.com:9000");
        //获取文件对象
        FileSystem fileSystem = FileSystem.get(configuration);
        //准备本地文件流
        String localFilePath = Hdfs.class.getClassLoader().getResource("my.log").getPath();
        System.out.println(localFilePath);        //查看本地路径
        FileInputStream inputStream = new FileInputStream(new File(localFilePath));
        //准备PUT文件路径对象
        String hdfsDirPath = "/user/hadoop/mapreduce/wordcount/input/my.log";
        Path path = new Path(hdfsDirPath);
        //获得输出流对象
        FSDataOutputStream outputStream = fileSystem.create(path);
        //PUT写入文件
        try{
            IOUtils.copyBytes(inputStream,outputStream,4096,false);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            IOUtils.closeStream(inputStream);
            IOUtils.closeStream(outputStream);
        }
    }
}
运行查看结果如下图:

这里写图片描述
程序读取到HDFS文件系统中文件的内容,并且无错误的返回了。那就去查看下HDFS中有没有成功上传my.log文件

未执行程序时
这里写图片描述
执行程序后
这里写图片描述
这里不知道为什么上传后所有者是乱码的,以后解决吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

再难也要坚持

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值