java 결합 HADOOP 클러스터 파일 업로드 다운로드

HDFS에 있는 파일을 업로드하고 다운로드하는 것은 집단에 대한 기본적인 작업이다. 이라는 책에서 파일의 업로드와 다운로드는 모두 코드의 실례가 있지만 HADOOP 클라이언트를 어떻게 설정하는지에 대해 잘 알지 못한다. 오랜 검색과 디버깅을 통해 집단을 사용하는 방법을 어떻게 설정하고 집단에 있는 파일을 조작할 수 있는 프로그램을 스스로 테스트할 수 있는지 정리했다.우선 다음과 같은 환경 변수를 구성해야 합니다.

hadoop_HOME="/home/work/tools/java/hadoop-client/hadoop"
for f in $hadoop_HOME/hadoop-*.jar; do
        hadoop_CLASSPATH=${hadoop_CLASSPATH}:$f
done
for f in $hadoop_HOME/lib/*.jar; do
        hadoop_CLASSPATH=${hadoop_CLASSPATH}:$f
done
hadoopvfs_HOME="/home/work/tools/java/hadoop-client/hadoop-vfs"
for f in $hadoopvfs_HOME/lib/*.jar; do
        hadoop_CLASSPATH=${hadoop_CLASSPATH}:$f
done
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/work/tools/java/hadoop-client/hadoop/lib/native/Linux-amd64-64/
여기서 LD_LIBRARY_PATH는 호출할 때 필요한 라이브러리의 경로입니다. hadoop_CLASSPATH는 Hadoop 클라이언트의 다양한jar 패키지입니다.
한 가지 주의해야 할 것은 하둡을 사용하지 않는 것이 가장 좋다는 것이다_HOME 이 변수, 이 변수는 시스템이 사용하는 환경 변수입니다. 충돌하지 않는 것이 좋습니다.
클래스를 컴파일하는 방법:

javac -classpath $CLASSPATH:$hadoop_CLASSPATH HDFSUtil.java
실행 방법:

java -classpath $CLASSPATH:$hadoop_CLASSPATH HDFSUtil
그러나 실제 사용 과정에서 No Permission 같은 오류가 발생하거나 코드에 문제가 없다는 것을 보증할 수 있는 상황에서 실행할 때도 기괴한 오류가 발생합니다
그럼 문제가 생겼어, 이게 뭐야?
답: 이것은 그룹에 대응하는 프로필을 설정하지 않았기 때문입니다
'HADOOP 권위 가이드'라는 책에서 배치된 것을 약화시켰기 때문에 집단을 구체적으로 사용할 때 문제가 발생한다. 어떻게 해결할 것인가.

this.conf = new Configuration(false);
conf.addResource("./hadoop-site.xml");
conf.addResource("./hadoop-default.xml");
conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
왜 그런지 책에는 간단할 뿐이다.
this.conf = new Configuration();
그것은 기본적으로 당신의 집단이 로컬에 있기 때문에 설정할 필요가 없지만, 실제 사용하는 과정에서 각 집단의 설정은 다르기 때문에 우리는 집단의 설정을 도입해야 한다
이것은 매우 중요한 점이다. 실제 사용 과정에서 우리는 모두 HADOOP의 클라이언트를 사용하고 이미 환경을 설정한 집단이기 때문에 우리는 현지의 설정을 잘 해야 한다
hadoop-site.xml과hadoop-default.xml 이 두 파일은 사용하는 클라이언트의 conf 디렉터리에서addResource에 디렉터리를 지정하면 됩니다
위에서 언급한 설정을 모두 조립한 후에야 이 프로그램이 진정으로 실행될 수 있기 때문에 설정은 매우 중요한 일환이다.
다음은 대응하는 도구의 코드입니다. 관심 있는 것은 보세요. 파일 흐름 방식을 사용해서 만든 것입니다. 이렇게 하면 FTP와 HDFS 사이의 파일 상호작용을 연결할 수 있습니다.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.io.*;

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

public class HDFSUtil {
  private String hdfs_node = "";
  private String hdfs_path = "";
  private String file_path = "";
  private String hadoop_site = "";
  private String hadoop_default = "";
  private Configuration conf = null;

  public HDFSUtil(String hdfs_node) {
    this.hdfs_node = hdfs_node;
  }

  public String getHdfsNode() {
    return this.hdfs_node;
  }

  public void setHdfsPath(String hdfs_path){
    this.hdfs_path = hdfs_path;
  }

  public String getHdfsPath(){
    return this.hdfs_path;
  }

  public void setFilePath(String file_path){
    this.file_path = file_path;
  }

  public String getFilePath(){
    return this.file_path;
  }

  public void setHadoopSite(String hadoop_site){
    this.hadoop_site = hadoop_site;
  }

  public String getHadoopSite(){
    return this.hadoop_site;
  }

  public void setHadoopDefault(String hadoop_default){
    this.hadoop_default = hadoop_default;
  }

  public String getHadoopDefault(){
    return this.hadoop_default;
  }

  public int setConfigure(boolean flag) {
    if (flag == false){
      if (this.getHadoopSite() == "" || this.getHadoopDefault() == ""){
        return -1;
      }
      else {
        this.conf = new Configuration(false);
        conf.addResource(this.getHadoopDefault());
        conf.addResource(this.getHadoopSite());
        conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
        conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
        return 0;
      }
    }
    this.conf = new Configuration();
    return 0;
  }

  public Configuration getConfigure() {
    return this.conf;
  }

  public int upLoad(String localName, String remoteName) throws FileNotFoundException, IOException {
    InputStream inStream = null;
    FileSystem fs = null;
    try{
      inStream = new BufferedInputStream(new FileInputStream(localName));
      fs = FileSystem.get(URI.create(this.hdfs_node), this.conf);
      OutputStream outStream = fs.create(new Path(remoteName) ,new Progressable() {
        public void progress(){
          System.out.print('.');
        }
      });

      IOUtils.copyBytes(inStream, outStream, 4096, true);
      inStream.close();
      return 0;
    } catch (IOException e){
      inStream.close();
      e.printStackTrace();
      return -1;
    }
  }

  public int upLoad(InputStream inStream, String remoteName) throws FileNotFoundException, IOException {
    FileSystem fs = null;
    try{
      fs = FileSystem.get(URI.create(this.hdfs_node), this.conf);
      OutputStream outStream = fs.create(new Path(remoteName) ,new Progressable() {
        public void progress(){
          System.out.print('.');
        }
      });

      IOUtils.copyBytes(inStream, outStream, 4096, true);
      inStream.close();
      return 0;
    } catch (IOException e){
      inStream.close();
      e.printStackTrace();
      return -1;
    }
  }

  public int donwLoad(String remoteName, String localName, int lines) throws FileNotFoundException, IOException {
    FileOutputStream fos = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    String str = null;
    OutputStreamWriter osw = null;
    BufferedWriter buffw = null;
    PrintWriter pw = null;
    FileSystem fs = null;
    InputStream inStream = null;
    try {
      fs = FileSystem.get(URI.create(this.hdfs_node + remoteName), this.conf);
      inStream = fs.open(new Path(this.hdfs_node + remoteName));
      fos = new FileOutputStream(localName);
      osw = new OutputStreamWriter(fos, "UTF-8");
      buffw = new BufferedWriter(osw);
      pw = new PrintWriter(buffw);
      isr = new InputStreamReader(inStream, "UTF-8");
      br = new BufferedReader(isr);
      while((str = br.readLine()) != null && lines > 0){
        lines--;
        pw.println(str);
      }
    } catch (IOException e){
      throw new IOException("Couldn't write.", e);
    } finally {
      pw.close();
      buffw.close();
      osw.close();
      fos.close();
      inStream.close()
    }
    return 0;
  }

  //main to test
  public static void main(String[] args){
    String hdfspath = null;
    String localname = null;
    String hdfsnode = null;
    int lines = 0;

    if (args.length == 4){
      hdfsnode = args[0];
      hdfspath = args[1];
      localname = args[2];
      lines = Integer.parseInt(args[3]);
    }
    else{
      hdfsnode = "hdfs://nj01-nanling-hdfs.dmop.baidu.com:54310";
      hdfspath = "/app/ps/spider/wdmqa/wangweilong/test/HDFSUtil.java";
      localname = "/home/work/workspace/project/dhc2-0/dhc/base/ftp/papapa";
      lines = 5;
    }
    HDFSUtil hdfsutil = new HDFSUtil(hdfsnode);
    hdfsutil.setFilePath(hdfsutil.getHdfsNode()+hdfspath);
    hdfsutil.setHadoopSite("./hadoop-site.xml");
    hdfsutil.setHadoopDefault("./hadoop-default.xml");
    hdfsutil.setConfigure(false);
    try {
      hdfsutil.donwLoad(hdfspath, localname, lines);
    } catch (IOException e){
      e.printStackTrace();
    }
  }
FTP의 파일 다운로드에 대해 알고 싶으면 이 글을 참조하십시오.
ftp 다운로드 도구
FTP와 HDFS 파일을 연결하려면 클래스를 만들고 이 두 글의 도구를 호출하는 인터페이스를 사용하면 됩니다. 자신이 쓴 코드는 실측이 유효합니다.
이상은 본문의 전체 내용입니다. 여러분이 자바를 익히는 데 도움이 되었으면 합니다.
글을 친구에게 공유하거나 댓글을 남기는 데 시간이 좀 걸리세요.우리는 당신의 지지에 진심으로 감사할 것입니다.

좋은 웹페이지 즐겨찾기