聲明:代碼來自《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?