05-HDFS的api *** 作

05-HDFS的api *** 作,第1张

05-HDFS的api *** 作 一、前期准备 1 解决winutils.exe的问题
  1. 把hadoop2.7.7(windows版)文件目录放到一个没有中文没有空格的路径下

链接:https://pan.baidu.com/s/17yXMvZeQSQgDGdsicoumJg
提取码:0l7w

  1. 在window中配置handoop的环境变量,并且加入path中

2 导入jar包

创建maven工程并导入jar包


  org.apache.hadoop
  hadoop-common
  2.7.7


  org.apache.hadoop
  hadoop-hdfs
  2.7.7


  org.apache.hadoop
  hadoop-client
  2.7.7

二、使用文件系统方式访问数据

在 java 中 *** 作 HDFS,主要涉及以下 Class:
Configuration:该类的对象封转了客户端或者服务器的配置;
FileSystem:该类的对象是一个文件系统对象,可以用该对象的一些方法来对文件进行 *** 作,通过 FileSystem 的静态方法 get 获得该对象。
get 方法从 conf 中的一个参数 fs.defaultFS 的配置值判断具体是什么类型的文件系统。如果我们的代码中没有指定 fs.defaultFS,并且工程 classpath下也没有给定相应的配置,conf中的默认值就来自于hadoop的jar包中的core-default.xml , 默 认 值 为 : file:/// , 则 获 取 的 将 不 是 一 个DistributedFileSystem 的实例,而是一个本地文件系统的客户端对象

public class StudyHdfs {
    FileSystem fileSystem;

    @Before
    public void init() throws IOException {
        Configuration configuration = new Configuration();
        //configuration.set("fs.default.name","hdfs://hadoop01:8020");
        configuration.set("fs.defaultFS", "hdfs://hadoop01:8020");
        fileSystem = FileSystem.get(configuration);
    }

    
    @Test
    public void createFilePath() throws IOException {
        fileSystem.mkdirs(new Path("/test/input"));
        fileSystem.close();
    }

    
    @Test
    public void uploadFile() throws IOException {
        fileSystem.copyFromLocalFile(new Path("C:\Users\zhanlijuan\Desktop\new 2.txt"), new Path("/test/input"));
        fileSystem.close();
    }

    
    @Test
    public void downloadFile() throws IOException {
        fileSystem.copyToLocalFile(new Path("/test/input/new 2.txt"), new Path("D:\b.txt"));
        fileSystem.close();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5575539.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-14
下一篇2022-12-14

发表评论

登录后才能评论

评论列表(0条)

    保存