hadoop hdfs2 Basic Filesystem Operations

一) 使用File shell方式,主要包括hadoop fs [command]和hdfs dfs [command]操作,具体的示例hadoop的referenece

二) 使用java api操作:

目前hadoop提供的文件操作的入口类主要有FileSystem和FileContext

步骤:

1. 获取org.apache.hadoop.conf.Configuration对象实例

2. 获取FileSystem或者FileContext实例

3. 通过FileSystem或者FileContext实例操作hadoop文件系统

示例1. create path in hadoop hdfs

Configeration conf = new Configeration();

FileSystem hdfs = FileSystem.get(conf);

Path path = new Path("pathName"); // ex: hdfs://localhost:9000/test and file:///filepath

hdfs.create(path);

hdfs.close();


示例2. create path in hadoop hdfs2

Configeration conf = new Configeration();

FileContext hdfs2 = FileContext.getFileContext(conf);
Path path = new Path("pathName");// ex: hdfs://localhost:9000/test and file:///filepath
// 这里搞不懂为什么要用EnumSet,纠结了半天还是没明白,直接用Enum方便多了

hdfs2.create(path, EnumSet.of(CreateFlag.CREATE), Options.CreateOpts.createParent());

//the same as operation delete

查看api可以知道FileContext提供了一个静态的方法:getLocalFSFileConext()来获取本地的FileConext对象.

hadoop1.x与hadoop2.x的HDFS的文件操作api全部由FileSystem转到了FileContext,当然向下兼容性可以让我们使用FileSystem操作.

需要注意的是,目前hadoop的配置上,hdfs的访问全是ALL,并且文件的权限也全是rw;这安全性以后研究.

获取一个目录下的文件列表:

FileStatus status = FileContext.getLocalFSFileContext().getFileStatus(path);

if (status.isDirectory()) {

RemoteIterator<FileStatus> fileList = FileContext.getLocalFSFileContext().listStatus(path);

while (fileList.hasNext()) {
FileStatus statu = fileList.next();
System.out.println(statu.getPath().getName());
}

}


使用FSDataInputStream于FSDataOutputStream对文件数据读写操作.

示例3. FSDataInputStream与FSDataOutputStream(分别继承java.io.DataInputStream与java.io.DataOutputStream)进行数据的操作.

下面完成了在hdfs文件系统中文件的拷贝:

FSDataInputStream in = null;
FSDataOutputStream out = null;
try {
in = FileContext.getLocalFSFileContext().open(path);
out = FileContext.getLocalFSFileContext().create(dest, EnumSet.of(CreateFlag.CREATE), Options.CreateOpts.donotCreateParent());

byte[] data = new byte[4096];
int length = 0;
while(0 < (length = in.read(data, 0, data.length))) {
out.write(data, 0, length);
}
} catch (AccessControlException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedFileSystemException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != in)
in.close();
if (null != out)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}


Hadoop获取文件对象数据:FileStatus实例,可以参考api


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值