java 결합 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 파일을 연결하려면 클래스를 만들고 이 두 글의 도구를 호출하는 인터페이스를 사용하면 됩니다. 자신이 쓴 코드는 실측이 유효합니다.
이상은 본문의 전체 내용입니다. 여러분이 자바를 익히는 데 도움이 되었으면 합니다.
글을 친구에게 공유하거나 댓글을 남기는 데 시간이 좀 걸리세요.우리는 당신의 지지에 진심으로 감사할 것입니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
38. Java의 Leetcode 솔루션텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.