溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Java Api怎么對HDFS進行操作

發布時間:2021-06-15 15:04:34 來源:億速云 閱讀:160 作者:Leah 欄目:編程語言

使用Java Api怎么對HDFS進行操作,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。

使用到的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 Api怎么對HDFS進行操作的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女