因为HDFS不同于一般的文件系统,所以Hadoop提供了强大的FileSystem API来操作HDFS.

核心类是FSDataInputStream和FSDataOutputStream

读操作:

我们用FSDataInputStream来读取HDFS中的指定文件(第一个实验),另外我们还演示了这个类的定位文件位置的能力,然后从指定位置开始读取文件(第二个实验)。

代码如下:

/*  


 */ 


package com.charles.hadoop.fs; 


 


 


import java.net.URI; 


 


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.apache.hadoop.io.IOUtils; 


 


/** 


 * 


 * Description: 查看Hadoop文件系统中的文件,利用hadoop FileSystem接口中的FSDataInputStream 


 * FSDataInputStream还具有流定位的能力,可以从文件的任意位置开始读取 


 * 


 * @author charles.wang 


 * @created May 26, 2012 12:28:49 PM 


 *  


 */ 


public class ReadFromHadoopFileSystem { 


 


    /** 


     * @param args 


     */ 


    public static void main(String[] args) throws Exception{ 


        // TODO Auto-generated method stub 


         


        //第一个参数传递进来的是hadoop文件系统中的某个文件的URI,以hdfs://ip 的theme开头 


        String uri = args[0]; 


        //读取hadoop文件系统的配置 


        Configuration conf = new Configuration(); 


        conf.set("hadoop.job.ugi", "hadoop-user,hadoop-user"); 


         


        //FileSystem是用户操作HDFS的核心类,它获得URI对应的HDFS文件系统 


        FileSystem fs = FileSystem.get(URI.create(uri),conf); 


        FSDataInputStream in = null; 


        try{ 


            //实验一:输出全部文件内容 


            System.out.println("实验一:输出全部文件内容"); 


            //让FileSystem打开一个uri对应的FSDataInputStream文件输入流,读取这个文件 


            in = fs.open( new Path(uri) ); 


            //用Hadoop的IOUtils工具方法来让这个文件的指定字节复制到标准输出流上 


            IOUtils.copyBytes(in, System.out,50,false);   


            System.out.println(); 


             


             


            //实验二:展示FSDataInputStream文件输入流的流定位能力,用seek进行定位 


            System.out.println("实验二:展示FSDataInputStream文件输入流的流定位能力,用seek进行定位"); 


             


            //假如我们要吧文件输出3次 


            //第一次输入全部内容,第二次输入从第20个字符开始的内容,第3次输出从第40个字符开始的内容 


            for (int i=1;i<=3;i++){ 


                in.seek(0+20*(i-1)); 


                System.out.println("流定位第 "+i+" 次:" ); 


                IOUtils.copyBytes(in, System.out,4096,false);  


            } 


        }finally{ 


            IOUtils.closeStream(in); 


        } 


 


    } 


 


} 

我们传入的命令行参数为我们要读的HDFS文件系统中某文件的URI:

hdfs://192.168.129.35:9000/user/hadoop-user/textfile.txt 

最终输出结果为:

实验一:输出全部文件内容 


This is a text file edited by charles to test the hadoop distributed file system's features. 


 


实验二:展示FSDataInputStream文件输入流的流定位能力,用seek进行定位 


流定位第 1 次: 


This is a text file edited by charles to test the hadoop distributed file system's features. 


流定位第 2 次: 


edited by charles to test the hadoop distributed file system's features. 


流定位第 3 次: