시작하며

Apache HDFS Command Guide (3.3.2.ver)

HDFS를 다루기 위한 CLI 명령어는 크게 쉘 명령어 방식과 Java API 방식으로 나뉜다. 리눅스 명령어와 매우 유사하여 사용하기 편리하다. 여기서는 자주 쓰는 기본 명령어와 Java 구현 예제를 함께 정리한다.

HDFS CLI 명령어

HADOOP Basic Cli Commands

Hadoop에서 CLI 명령어는 아래 두 가지 커맨드를 사용할 수 있다. 두 가지 중 편한 것을 선택해 사용하면 된다.

# 기본 명령어
hadoop fs -help # 혹은 hdfs dfs
 
# 디렉토리 생성
hadoop fs -mkdir {디렉토리 경로} # 혹은 hdfs dfs
 
# 로컬에 있는 파일을 hdfs로 전송
hadoop fs -put {로컬경로} {HDFS경로} # 혹은 copyFromLocal
 
# hdfs로 있는 파일을 로컬 전송
hadoop fs -get {HDFS경로} {로컬경로} # 혹은 copyToLocal

Basic Cli Commands with JAVA

위의 커맨드들은 하둡에서 제공하는 .jar 파일들을 통해 Java 프로그램으로도 구현할 수 있다.

// FileSystemPrint
String uri = args[0];
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
try( InputStream in = fs.open(new Path(uri))){
    IOUtils.copyBytes(in, System.out, 4096, false);
}
 
// ListStatus
String uri = args[0];
Configuration config = new Configuration();
 
FileSystem fs = FileSystem.get(URI.create(uri), config);
Path path = new Path(uri);
 
FileStatus[] status = fs.listStatus(path);
Path[] listPaths = FileUtil.stat2Paths(status);
for ( Path p : listPaths){
    System.out.println(p);
}
 
// -put
String src = args[0];
String dst = args[1];
 
InputStream in = new BufferedInputStream(new FileInputStream(src));
 
Configuration config = new Configuration();
FileSystem fs = FileSystem.get(URI.create(dst), config);
OutputStream out = fs.create(new Path(dst));
 
IOUtils.copyBytes(in, out, 4096, true);
 
// delete
String uri = args[0];
 
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
 
Path path = new Path(uri);
if (fs.exists(path)){
    fs.delete(path, false);
}

정리하며

HDFS CLI는 hadoop fs 또는 hdfs dfs 두 가지 방식으로 사용할 수 있으며, 리눅스 파일시스템 명령어와 거의 동일한 인터페이스를 제공한다. Java API를 통해서도 동일한 파일시스템 작업을 프로그래밍 방식으로 구현할 수 있으므로, 배치 작업이나 데이터 파이프라인을 구성할 때 유용하게 활용할 수 있다.