欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

使用Java Api操作HDFS过程详解

时间:2022-02-19 09:40:01|栏目:JAVA代码|点击:

如题 我就是一个标题党 就是使用JavaApi操作HDFS,使用的是MAVEN,操作的环境是Linux

首先要配置好Maven环境,我使用的是已经有的仓库,如果你下载的jar包 速度慢,可以改变Maven 下载jar包的镜像站改为 阿里云。

贴一下 pom.xml

使用到的jar包

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.10</version>
    </dependency>
    
    <!-- hadoop Client -->
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client</artifactId>
      <version>${hadoop.version}</version>
    </dependency>
    
</dependencies>

然后就是操作HDFS的代码

package com.zuoyan.hadoop.hdfs;

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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;

/**
 * use java api operate hdfs
 * 
 * @author beifeng
 * 
 */
public class HdfsApp {

  // get FileSystem
  public static FileSystem getFileSystem() throws Exception {
    Configuration conf = new Configuration();
    FileSystem fileSystem = FileSystem.get(conf);
    return fileSystem;
  }

  public static void read(String fileName) throws Exception {

    FileSystem fileSystem = getFileSystem();

    // read Path
    Path readPath = new Path(fileName);

    FSDataInputStream inStream = fileSystem.open(readPath);

    try {

      IOUtils.copyBytes(inStream, System.out, 4096, false);

    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    } finally {
      // if Exception close Stream
      IOUtils.closeStream(inStream);
    }
  }

  public static void main(String[] args) throws Exception{
      
      //String fileName = "/user/beifeng/mapreduce/wordcount/input/wc.input";
      //read(fileName);
    
      FileSystem fileSystem = getFileSystem();
      //write path
      String putFileName = "/user/beifeng/put-wc.input";
      
      Path writePath = new Path(putFileName);
      
      FSDataOutputStream outputStream = fileSystem.create(writePath);
      
      FileInputStream inputStream = new FileInputStream(
          new File("/opt/modules/hadoop-2.5.0/wc.input"));
      
      try {
        IOUtils.copyBytes(inputStream, outputStream, 4096,false);
      } catch (Exception e) {
        // TODO: handle exception
        inputStream.close();
        outputStream.close();
      }    
  }
}

思路

可以使用Java操作hdfs的api 制作一个基于HDFS的 云盘 ,可以对文件进行 上传 、删除、移动目录 、查看目录,但是不可以对文件的内容进行修改!

上一篇:java常用工具类 XML工具类、数据验证工具类

栏    目:JAVA代码

下一篇:springboot配置templates直接访问的实现

本文标题:使用Java Api操作HDFS过程详解

本文地址:http://www.codeinn.net/misctech/193937.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有