Java API 조작 HDFS

4787 단어 hadoop
hdfs 는 생산 응용 에서 주로 클 라 이언 트 의 개발 이다.그 핵심 절 차 는 hdfs 가 제공 하 는 api 에서 HDFS 의 방문 클 라 이언 트 대상 을 구축 한 다음 에 이 클 라 이언 트 대상 조작(삭제 및 검사)HDFS 의 파일 1.1 을 통 해 개발 환경 을 구축 하 는 것 이다.1.org.apache.hadop hadop-client 2.8.3 도입
주:jar 패 키 지 를 수 동 으로 도입 하려 면 hdfs 의 jar 패키지-hadop 설치 디 렉 터 리 의 share 아래 2,window 에서 개발 한 설명 은 Liux 에서 hadop 응용 개발 을 권장 하 며 호환성 문제 가 없 을 것 입 니 다.window 에서 클 라 이언 트 애플 리 케 이 션 개발 을 하려 면 다음 과 같은 환경 을 설정 해 야 합 니 다.A.windows 의 한 디 렉 터 리 에서 hadop 의 설치 패키지 B 를 풀 고 설치 패키지 에 있 는 lib 와 bin 디 렉 터 리 를 windows 버 전 플랫폼 에서 컴 파일 한 로 컬 라 이브 러 리 로 C 를 교체 하 며 window 시스템 에 HADOOP 을 설정 합 니 다.HOME 는 압축 을 푸 는 패키지 D 를 가리 키 며 windows 시스템 path 변수 에 hadop 을 추가 한 bin 디 렉 터 리 1.2 api 의 클 라 이언 트 대상 이 자바 에서 hdfs 를 조작 하 는 것 을 가 져 옵 니 다.먼저 클 라 이언 트 인 스 턴 스 Configuration conf=new Configuration()FileSystem fs=FileSystem fs=FileSystem.get(conf)을 가 져 옵 니 다.
우리 의 작업 목 표 는 HDFS 이기 때문에 얻 은 fs 대상 은 Distributed FileSystem 의 인 스 턴 스 여야 합 니 다.get 방법 은 어디에서 구체 적 인 실례 화 된 클 라 이언 트 클래스 를 판단 합 니까?conf 의 매개 변수 fs.defaultFS 의 설정 값 을 판단 합 니 다.
코드 에 fs.defaultFS 가 지정 되 어 있 지 않 고 프로젝트 classpath 에 도 해당 하 는 설정 이 지정 되 어 있 지 않 으 면 conf 의 기본 값 은 hadop 의 jar 패키지 의 core-default.xml 에서 나 옵 니 다.기본 값 은 file://입 니 다.Distributed FileSystem 의 인 스 턴 스 가 아니 라 로 컬 파일 시스템 의 클 라 이언 트 대상 을 가 져 옵 니 다.
1.4 HDFS 클 라 이언 트 조작 데이터 코드 예시:1.4.1 파일 의 삭제 변경 public class HdfsClient{
FileSystem fs = null;

@Before
public void init() throws Exception {

    //           ,      :      hdfs URI
    //   FileSystem.get()               hdfs        ,  hdfs     
    // new Configuration();   ,      jar   hdfs-default.xml
    //      classpath  hdfs-site.xml
    Configuration conf = new Configuration();
    conf.set("fs.defaultFS", "hdfs://hdp-node01:9000");
    /**
     *      : 1、           2、classpath            3、           
     */
    conf.set("dfs.replication", "3");

    //     hdfs      ,    ,       DistributedFileSystem   
    // fs = FileSystem.get(conf);

    //        , conf        "fs.defaultFS"  ,  ,             hadoop  
    fs = FileSystem.get(new URI("hdfs://hdp-node01:9000"), conf, "hadoop");

}

/**
 *  hdfs    
 * 
 * @throws Exception
 */
@Test
public void testAddFileToHdfs() throws Exception {

    //              
    Path src = new Path("g:/redis-recommend.zip");
    //     hdfs     
    Path dst = new Path("/aaa");
    fs.copyFromLocalFile(src, dst);
    fs.close();
}

/**
 *  hdfs            
 * 
 * @throws IOException
 * @throws IllegalArgumentException
 */
@Test
public void testDownloadFileToLocal() throws IllegalArgumentException, IOException {
    fs.copyToLocalFile(new Path("/jdk-7u65-linux-i586.tar.gz"), new Path("d:/"));
    fs.close();
}

@Test
public void testMkdirAndDeleteAndRename() throws IllegalArgumentException, IOException {

    //     
    fs.mkdirs(new Path("/a1/b1/c1"));

    //       ,        ,  2    true
    fs.delete(new Path("/aaa"), true);

    //          
    fs.rename(new Path("/a1"), new Path("/a2"));

}

/**
 *       ,     
 * 
 * @throws IOException
 * @throws IllegalArgumentException
 * @throws FileNotFoundException
 */
@Test
public void testListFiles() throws FileNotFoundException, IllegalArgumentException, IOException {

    //   :        ,   List     
    RemoteIterator listFiles = fs.listFiles(new Path("/"), true);

    while (listFiles.hasNext()) {
        LocatedFileStatus fileStatus = listFiles.next();
        System.out.println(fileStatus.getPath().getName());
        System.out.println(fileStatus.getBlockSize());
        System.out.println(fileStatus.getPermission());
        System.out.println(fileStatus.getLen());
        BlockLocation[] blockLocations = fileStatus.getBlockLocations();
        for (BlockLocation bl : blockLocations) {
            System.out.println("block-length:" + bl.getLength() + "--" + "block-offset:" + bl.getOffset());
            String[] hosts = bl.getHosts();
            for (String host : hosts) {
                System.out.println(host);
            }
        }
        System.out.println("-------------- angelababy      --------------");
    }
}

/**
 *           
 * 
 * @throws IOException
 * @throws IllegalArgumentException
 * @throws FileNotFoundException
 */
@Test
public void testListAll() throws FileNotFoundException, IllegalArgumentException, IOException {

    FileStatus[] listStatus = fs.listStatus(new Path("/"));

    String flag = "d--             ";
    for (FileStatus fstatus : listStatus) {
        if (fstatus.isFile())  flag = "f--         ";
        System.out.println(flag + fstatus.getPath().getName());
    }
}

}

좋은 웹페이지 즐겨찾기