对于一个文件系统来说,如何能够方便的读取文件系统中的内容是使用者很关心的一个问题,对于hadoop这样一个分布式云计算平台来说,它的hdfs文件系统当然提供了一个方便的文件访问接口进行文件系统内容的读取.我们可以通过Hadoop URL的方式进行读取,也可以通过Hadoop提供的文件系统的API进行文件读取.今天首先介绍一下通过URL的方式进行Hadoop文件系统的读取:
package tong.li.hadoop.test;
import java.io.InputStream;
import java.net.URL;
import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;
import org.apache.hadoop.io.IOUtils;
public class DataReadByURL {
static{
URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
}
public static void main(String[] args) throws Exception{
InputStream in = null;
try{
in = new URL("hdfs://127.0.0.1:9000/data/mydata").openStream();
IOUtils.copyBytes(in,System.out,2048,false);
}finally{
IOUtils.closeStream(in);
}
}
}
上面的程序很简单,具体细节无需解释.
上面我们讨论了利用HDFS的url的方式读取HDFS内文件内容的方法,今天我们讨论使用HDFS的API对HDFS内的文件进行读取.
HDFS主要通过FileSystem类来完成对文件的打开操作.和java使用java.io.File来表示文件很不相同,hadoop的HDFS文件系统中的文件是通过Hadoop的Path类来表示的.
FileSystem通过静态方法 get(Configuration conf)来获得FileSystem的实例.通过该实例,我们可以通过FileSystem的open,seek等方法来实现对hdfs的访问,具体的方法如下所示:
public FSDataInputStream open(Path f) throws IOException
public abstract FSDataInputStream open(Path f, int bufferSize)
throws IOException;
通过FileSystem的源代码可以看到,最终open方法落到一个抽象方法public abstract FSDataInputStream open(Path f, int bufferSize)来实现文件的打开,具体的实现方式由继承自FileSystem的具体文件系统的实现来决定.
有了上面的简单解释,我们来看一个通过HDFS的API来访问文件系统的例子:
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
public class HDFSCatWithAPI {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// 指定Configuration
Configuration conf = new Configuration();
//定义一个DataInputStream
FSDataInputStream in = null;
try{
//得到文件系统的实例
FileSystem fs = FileSystem.get(conf);
//通过FileSystem的open方法打开一个指定的文件
in = fs.open(new Path("hdfs://localhost:9000/user/myname/input/fixFontsPath.sh"));
//将InputStream中的内容通过IOUtils的copyBytes方法拷贝到System.out中
IOUtils.copyBytes(in,System.out,4096,false);
//seek到position 1
in.seek(1);
//在执行一边拷贝输出工作
IOUtils.copyBytes(in,System.out,4096,false);
}finally{
IOUtils.closeStream(in);
}
}
}
输出如下:
#!/bin/sh
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version
..........(中间内容略去)
</map:sitemap>
EOF
!/bin/sh
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version
..........(中间内容略去)
</map:sitemap>
EOF
上面的例子简单介绍了Hdfs读取文件的API.值得提出的是seek方法,这里我们使用了seek(1)可以看到第二遍输出比第一遍少了一个#号,这就是seek(1)的结果.另外seek方法相对来说是一个代价比较大的操作(具体可以参见DFSInputStream中对于seek,read等的实现).因此发挥hadoop的特长还是通过Stream数据来处理数据.