IDEA中HDFS-文件基本操作API实列

17 篇文章 0 订阅
10 篇文章 0 订阅

创建客户端java项目,实现以下功能:
① 通过api 连接 hdfs; 熟悉不同的连接方式以及优先级
② 实现文件上传;
③ 实现文件下载;
④ 了解其他文件管理的方法。
⑤ 在编程的过程中,简单了解客户端项目的创建:maven 项目;本地jar包项目

a. 创建maven项目, File —> Project ----> maven (2020 版本默认已安装maven组件)
在这里插入图片描述在这里插入图片描述在这里插入图片描述b. 修改pom.xml

# 将依赖的jar包信息添加到maven的配置文件,idea提示自动下载确定即可(或手动右键 pom.xml 选择maven的 reload project 或 download source)
# 包括单元测试 junit,hadoop-client,hadoop-common和hadoop-hdfs
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>2.7.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.7.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-hdfs</artifactId>
        <version>2.7.7</version>
    </dependency>
</dependencies>

c. 添加文件, src>main中新建java文件,resource 目录下添加 配置文件,如core-site.xml,hfds-site.xml等

Hadoop上传测试

① 创建FileSytem文件系统对象,优先级由下至上
连接HDFS,通过配置文件的方式创建FileSystem实例 resource
连接HDFS,通过configuration创建FileSytem实例。

/*
* 通过configuration配置hdfs连接信息
* 抛异常--去掉IO,因为Exception是最高级别异常,避免反复修改
*/
public void getFileSystemWithConf() throws Exception{
    //实例化configuration对象
    Configuration conf = new Configuration();
    //设置基本参数,同6大配置文件,key-value
    conf.set("fs.defaultFs","hdfs://192.168.38.131:9000");
    //获取文件系统操作对象
    FileSystem fs = FileSystem.get(conf);
    //显示fs的模式
    boolean ostype = fs instanceof DistributedFileSystem; 
    String typeinfo = ostype ? "分布式操作系统":"本地操作系统";
    System.out.println("当前操作的系统是"+typeinfo);
    fs.close();
    
}

连接HDFS,创建FileSystem时采用newInstance实例化方法。

public void getFileSytemWithNewInstance() throws  IOException {
    //实例化configuration对象
    Configuration conf = new Configuration();
    //设置基本参数,同6大配置文件,key-value
    conf.set("fs.defaultFs","hdfs://192.168.38.131:9000");
    //获取文件系统操作对象
    FileSystem fs = FileSystem.newInstance(conf);
    //显示fs的模式
    boolean ostype = fs instanceof DistributedFileSystem; 
    String typeinfo = ostype ? "分布式操作系统":"本地操作系统";
    System.out.println("当前操作的系统是"+typeinfo);
    fs.close();
}

连接HDFS,通过uri方式创建FileSystem实例。

/*
* 通过uri 配置hdfs连接信息
*/
public void getFileSystemWithUri() throws URISyntaxException, IOException, InterruptedException {
    //实例化configuration对象
    Configuration conf = new Configuration();
    //传入uri参数,获取文件系统操作对象
    FileSystem fs = FileSystem.get(new URI("hdfs://192.168.38.131:9000"), conf, "hadoop");
    /*
    *  String uri= "hdfs://192.168.38.131:9000/wordcount.txt"; //可简写,直接写文件名称
    *  FileSystem fileSystem = FileSystem.get(URI.create(uri), configuration,"hadoop");
    */
    //显示fs的模式
    boolean ostype = fs instanceof DistributedFileSystem;
    String typeinfo = ostype ? "分布式操作系统":"本地操作系统";
    System.out.println("当前操作的系统是"+typeinfo);
    fs.close();
}

② 显示FileSystem的目录或文件信息
遍历文件

public void listFiles() throws URISyntaxException, IOException, InterruptedException {

       //实例化configuration对象
       Configuration conf = new Configuration();
       //传入uri参数,获取文件系统操作对象
       FileSystem fs = FileSystem.get(new URI("hdfs://192.168.38.131:9000"), conf, "hadoop");
       //定义目标位置
       Path dst = new Path("/");
       //利用迭代器遍历目标位置
       RemoteIterator<LocatedFileStatus> iterator = fileSystem.listFiles(dst,true);
       while (iterator .hasNext()){
           LocatedFileStatus lfs = iterator.next();
           System.out.println("文件路径:"+lfs.getPath() );
           System.out.println("文件名称:"+lfs.getPath().getName() );
           System.out.println("文件副本数:"+lfs.getReplication() );
           BlockLocation[] blocks = lfs.getBlockLocations();
           System.out.println("文件block数量:"+blocks.length );
           System.out.println("文件block大小:"+lfs.getBlockSize() +" bytes");//默认128M
       }
       fs.close();
}

遍历文件(非迭代)

public void judge() throws Exception {
        //1.创建配置文件信息对象
        Configuration conf = new Configuration();

        //2.获取文件系统
        FileSystem fs = FileSystem.get(new URI("hdfs://bigdata111:9000/"), conf, "root");

        //3.遍历所有内容(文件、非文件)
        //listStatus()不支持迭代
        FileStatus[] listStatus = fs.listStatus(new Path("/"));
        for(FileStatus status:listStatus){
            //判断是否是文件
            if(status.isFile()){
                //ctrl+d:复制一行
                //ctrl+s:剪切一行,也可以用来删除一行
                System.out.println(status.getPath().getName()+"是文件");
            }else{
                System.out.println(status.getPath().getName()+"是目录");
            }
        }
    }

③ 文件操作类(增、删文件或目录)
创建目录(可递归创建目录)

//创建目录
 public void mkdirHDFS() throws Exception {
         //1.创建配置信息对象
         Configuration conf = new Configuration();  
         //2.连接文件系统
         //final URI uri :HDFS地址
         // final Configuration conf:配置信息
         // String user:Linux用户名
         FileSystem fs = FileSystem.get(new URI("hdfs://192.168.38.131:9000/"), conf, "hadoop");
         //创建目录
         fs.mkdirs(new Path("/output"));
         //关闭
         fs.close(); 
}

删除文件

//创建目录
  public void deleteFromHDFS() throws Exception {
        //创建配置信息对象
        Configuration conf = new Configuration();
        //连接文件系统
        FileSystem fs = FileSystem.get(new URI("hdfs://192.168.38.131:9000/"), conf, "hadoop");
        //删除文件
        //Path var1 :地址
        //boolean var2:是否递归删除
        fs.delete(new Path("/output"),true);
        //关闭
        fs.close(); 
    }

④ 文件上传 (将本地文件上传到服务器,待上传文件路径为 E:\HadoopWork\files\input\dfs_test.txt,目标路径为 /tmp )

 public void putFileToHDFS() throws Exception {
        //创建配置信息对象与FileSystem对象
        Configuration conf = new Configuration();  
        FileSystem fs = FileSystem.get(new URI("hdfs://192.168.38.131:9000/"),conf,"hadoop");
        //上传本地文件的路径
        Path src = new Path("E:\\HadoopWork\\files\\input\\dfs_test.txt");
        //要上传到HDFS的路径
        Path dst = new Path("/tmp");
        //以拷贝的方式上传  从src-->dst
        fs.copyFromLocalFile(src,dst);
        fs.close();
}

io文件流操作

public void putFileToHDFSIO() throws URISyntaxException, IOException, InterruptedException {
    //创建配置信息对象 Configuration:配置
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://192.168.38.131:9000/"),conf,"hadoop");
    //创建本地系统的输入流
    FileInputStream fis = new FileInputStream(new File("E:\\HadoopWork\\files\\input\\dfs_test.txt"));
    //输出路径
    Path writePath = new Path("/input/dfs_test_new.txt");
    //输出流(FSDataOutputStream属于hadoop)
    FSDataOutputStream  fos = fs.create(writePath);
    //流对接
    //InputStream in:输入流
    //OutputStream out:输出流
    //int buffSize:缓冲区大小
    //boolean close:是否关闭
    IOUtils.copyBytes(fis,fos,4*1024,true);
    fs.close();
}

⑤ 文件下载 ( 此处磁盘确认目标路径存在 )

 public void getFileFromHDFS() throws Exception {
    //创建配置信息对象 Configuration:配置
    Configuration conf = new Configuration();
    //找到文件系统
    FileSystem fs = FileSystem.get(new URI("hdfs://192.168.38.131:9000/"), conf, "hadoop");
    //下载文件
    //boolean delSrc :是否将源文件删除
    //boolean useRawLocalFileSystem:是否校验文件
    fs.copyToLocalFile(false,new Path("/tmp/dfs_test.txt"),new Path("E:\\HadoopWork\\files\\output"),true);
    fs.close();
}

IO文件流方式下载文件

public void getFileFromHDFSIO() throws Exception {
    //创建配置信息对象
    Configuration conf = new Configuration();
    //连接文件系统
    FileSystem fs = FileSystem.get(new URI("hdfs://192.168.38.131:9000/"), conf, "root");
    //读取路径
    Path readPath = new Path("/tmp/dfs_test.txt");
    //输入
    FSDataInputStream fis = fs.open(readPath);
    boolean print = true;
    //输出到控制台
    //InputStream in:输入流
    //OutputStream out:输出流
    //int buffSize:缓冲区大小
    //boolean close:是否关闭
    // IOUtils.copyBytes(fis, System.out, 4 * 1024, false);
    File file = new File("E:\\HadoopWork\\files\\output\\test.txt");
    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    IOUtils.copyBytes(fis, out, 4096, !print);
    if (print) {
        fis.seek(0);  //输入流从新回到文件开始的位置
        IOUtils.copyBytes(fis, System.out, 4096, false);
    }
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值