본문 바로가기

Bigdata/hadoop

[Hadoop] HDFS에 파일 쓰기

이번 글에서는 하둡 hdfs에 파일을 저장하는 방법을 알아보겠다.

기본적인 형태는 일반 파일 입출력과 크게 차이가 있지 않다.

첫번째로는 하둡에 저장하기 위해 DFSOutputStream을 추상화한 FSDataOutputStream을 이용하는점.

두번째로는 FileSystem과 Path 객체를 이용해 hdfs의 경로 및 기타 설정을 해야하는 차이가 있을 뿐이다.


아래는 예제 코드이다.

public static void main(String[] args) throws Exception {
    FSDataOutputStream fout = null;
    try {
        Path path = new Path("hdfs://NaeNode:port/path/file");
        String data = "data";
        FileSystem fileSystem = FileSystem.get(new Configuration());
        if (!fileSystem.exists(path)) {
            fout = fs.create(path); 
        } else {
            fout = fs.append(path)
        }
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fout)
        );
        bufferedWriter.write(data);
        bufferedWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}