上次我们讨论了利用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 abstractFSDataInputStream 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