욱'S 노트

HDFS - FileSystem API 맛보기 본문

Programming/Hadoop

HDFS - FileSystem API 맛보기

devsun 2014. 12. 18. 14:56

HDFS를 다루기 위해서 파일시스템을 추상화한 클래스인 FileSystem 클래스를 제공한다.

Outline을 보면 알겠지만, 파일처리에 대한 모든 api를 제공한다.


일단 간단하게 디렉토리를 한번 만들어보자. 메소드가 명시적이라 어려운이 없을것이라고 생각된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
import java.io.IOException;
 
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.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class SimpleFileSytemTest {
    private static final String CONFIG_PATH = "/Users/devsun/dev/hadoop-2.5.2/etc/hadoop/core-site.xml";
    private static final String FILE_PATH = "/user/devsun/test/README.txt";
    
    private final Logger logger = LoggerFactory.getLogger(SimpleFileSytemTest.class);
    
    private Configuration configuration;
    
    @Before
    public void setup() {
        configuration = new Configuration();
        configuration.addResource(new Path(CONFIG_PATH));
    }
    
    @Test
    public void testMakeDir() throws IllegalArgumentException, IOException {
        boolean success = FileSystem.get(configuration).mkdirs(new Path("/user/devsun/test2"));
        Assert.assertEquals(true, success);
    }
}
 
cs


다음 소스는 파일을 읽는 소스이다. 일단 파일을 하나 올려보자.


$ bin/hdfs dfs -put README.txt test


점점 이 정도는 식은죽먹기가 되어간다. 아래는 파일을 읽는 소스이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
    @Test
    public void testFileRead() throws IOException {
        FileSystem fileSystem = null;
        FSDataInputStream inputStream = null;
        StringBuilder contents = new StringBuilder();
        
        try {
            fileSystem = FileSystem.get(configuration);
            
            Path path = new Path(FILE_PATH);
            
            inputStream = fileSystem.open(path);
                    
            byte[] bytes = new byte[4096];
            
            while ( inputStream.read(bytes) != -1) {
                contents.append(new String(bytes));
            }
            
            logger.info("Contents : {}",contents.toString());
            
        } catch (IOException e) {
            logger.error("Error occured.", e);
            throw e;
        } finally {
            inputStream.close();
            fileSystem.close();
        }        
    }
 
cs


'Programming > Hadoop' 카테고리의 다른 글

MapReduce 시작하기  (0) 2014.12.22
MapReduce 개요  (0) 2014.12.22
HDFS 개발 시작하기(java)  (0) 2014.12.18
HDFS 개요  (0) 2014.12.17
HDFS 다루기 - File system shell  (0) 2014.12.17
Comments