[java] 자바와 아파치 하둡의 분산 파일 액세스 기술

이번 글에서는 자바와 아파치 하둡의 분산 파일 액세스 기술에 대해 알아보겠습니다. 분산 파일 액세스는 대규모 데이터 처리를 위해 필수적인 요소로 사용되는 기술입니다. 자바는 다양한 하둡 API와 라이브러리를 통해 분산 파일 액세스를 지원하며, 여러 가지 방법을 통해 파일을 읽고 쓸 수 있습니다.

1. 자바와 하둡 파일 시스템

자바에서 하둡의 분산 파일 시스템에 접근하기 위해 org.apache.hadoop.fs 패키지를 사용합니다. 이 패키지에는 하둡 파일 시스템에 액세스하기 위한 여러 가지 클래스와 인터페이스가 포함되어 있습니다. 주요 클래스로는 FileSystem, Path, FSDataInputStream, FSDataOutputStream 등이 있습니다.

2. 파일 읽기와 쓰기

자바에서 하둡 파일 시스템을 통해 파일을 읽거나 쓰기 위해 다음과 같은 과정을 거칩니다.

파일 읽기

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FSDataInputStream;

public class FileReadExample {
    public static void main(String[] args) {
        try {
            // 파일 시스템 객체 생성
            FileSystem fs = FileSystem.get(new Configuration());

            // 읽을 파일 경로 생성
            Path filePath = new Path("hdfs://localhost:9000/input/sample.txt");

            // 파일 열기
            FSDataInputStream in = fs.open(filePath);

            // 파일 읽기
            byte[] buffer = new byte[1024];
            int bytesRead = in.read(buffer);

            // 읽은 파일 내용 출력
            System.out.println(new String(buffer, 0, bytesRead));

            // 파일 닫기
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

파일 쓰기

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FSDataOutputStream;

public class FileWriteExample {
    public static void main(String[] args) {
        try {
            // 파일 시스템 객체 생성
            FileSystem fs = FileSystem.get(new Configuration());

            // 쓸 파일 경로 생성
            Path filePath = new Path("hdfs://localhost:9000/output/sample.txt");

            // 파일 열기
            FSDataOutputStream out = fs.create(filePath);

            // 파일 쓰기
            String content = "Hello, Hadoop!";
            out.write(content.getBytes());

            // 파일 닫기
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 하둡 클러스터 환경 설정

자바 애플리케이션이 하둡 클러스터에 액세스할 수 있도록 환경을 설정해야 합니다. 일반적으로 core-site.xml, hdfs-site.xml 등의 설정 파일을 사용하여 클러스터의 네임노드 주소와 포트 번호를 지정합니다.

참고 자료