Hadoop FileSystem類


聲明:代碼來自《Hadoop應用技術開發詳解》4.7.2,版權歸作者所有。

1. 概述

  文件在Hadoop中表示為一個Path對象,可以把路徑看做是Hadoop文件系統的URI,例如:hdfs://master:9000/user/hadoop/study/mr/WordCount/input/file1.txt

  FileSystem是Hadoop中文件系統的抽象父類,Configuration對象封裝了客戶端或者服務器端的配置信息。

  通過FileSystem類訪問Hadoop中的文件,基本方法是首先通過FileSystem類的get方法獲取一個實例,然后調用它的open方法獲得輸入流。

 

2. 代碼

file: hdfs\FileSystemReader.java

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;

import java.io.InputStream;
import java.net.URI;

/**
 * @version 1.0.0, 2015/2/2
 */
public class FileSystemReader {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String uri = args[0];
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        InputStream inputStream = null;

        try {
            inputStream = fs.open(new Path(uri));
            IOUtils.copyBytes(inputStream, System.out, 4096, false);
        } finally {
            IOUtils.closeStream(inputStream);
        }
    }
}

 

3. 運行結果

[hadoop@master hdfs]$ hadoop jar FileSystemReader.jar hdfs://master:9000/user/hadoop/study/mr/WordCount/input/file1.txt
Hello, i love coding
are you ok?
Hello, i love hadoop
areyou ok?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM