hadoop文件系统的读取(二)

本文介绍如何使用Hadoop HDFS API进行文件读取操作,包括FileSystem类的使用方法及示例代码,展示了如何通过open方法打开文件并利用seek方法定位文件位置。

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


上面的例子简单介绍了Hdfs读取文件的API.值得提出的是seek方法,这里我们使用了seek(1)可以看到第二遍输出比第一遍少了一个#号,这就是seek(1)的结果.另外seek方法相对来说是一个代价比较大的操作(具体可以参见DFSInputStream中对于seek,read等的实现).因此发挥hadoop的特长还是通过Stream数据来处理数据.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值