首页 > 编程 > Java > 正文

使用Java Api操作HDFS过程详解

2019-11-26 08:31:48
字体:
来源:转载
供稿:网友

如题 我就是一个标题党 就是使用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的 云盘 ,可以对文件进行 上传 、删除、移动目录 、查看目录,但是不可以对文件的内容进行修改!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表