hdfs操作java API

本文详细介绍了Java中与Hadoop分布式文件系统(HDFS)交互的关键类,如Configuration、FileSystem、Path、FSDataOutputStream、BufferedReader和FileStatus,涵盖了文件创建、读写、检查和元数据获取等内容。
摘要由CSDN通过智能技术生成

1.Configuration类——cof对象

(1)创建

Configuration conf = new Configuration();  
conf.set("fs.defaultFS", "hdfs://localhost:9000"); 
conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");

2.FileSystem类——fs对象

(1)创建

FileSystem fs = FileSystem.get(new URI(conf.get("fs.defaultFS")), conf); 

(2)方法

  • fs.create(hdfsPath, true)  写文件,true表覆盖
  • fs.open(hdfsPath) 读文件
  • fs.append
  • fs.exists(hdfsPath) 判断hdfs文件是否存在
  • fs.close()

3.Path类 

(1)创建

String localFilePath = "/home/hadoop/xsyTest.txt"; // 本地文件路径  
String hdfsFilePath = "input/xsyTest.txt"; // HDFS目标路径
//String hdfsFilePath = "/user/hadoop/input/xsyTest.txt"; // 或该完整路径   
Path localPath = new Path(localFilePath);  
Path hdfsPath = new Path(hdfsFilePath);

(2)hdfs文件是否存在

import org.apache.hadoop.fs.*;
FileSystem fs = FileSystem.get(new URI(conf.get("fs.defaultFS")), conf);  
Path hdfsPath = new Path(hdfsFilePath); 
boolean flag = fs.exists(hdfsPath)

(3)本地文件是否存在

import java.io.*;
String localFilePath = "/home/hadoop/xsyTest.txt"; // 本地文件路径
File fs = new File(localFilePath);
boolean flag = fs.exists();

4.FSDataOutputStream类:FileSystem之上

(1)创建

FSDataOutputStream out = fs.create(hdfsPath, true); // 第二个参数true表示重名覆盖
FSDataOutputStream out = fs.create(hdfsPath); //纯上传未重名

 4.FSDataOutputStream类:FileSystem之上

(1)创建

FSDataInputStream in = fs.open(hdfsPath);

5.BufferedReader类:读文件,FSDataIutputStream之上

(1)创建d对象

(2)读文件d.readLine()

BufferedReader d = new BufferedReader(new InputStreamReader(in))
String line = null;
while ( (line = d.readLine()) != null ) {
    System.out.println(line);
}

6.FileStatus类:封装了文件系统中文件和目录的元数据,包括文件的长度、块大小、备份数、修改时间、所有者以及权限等信息。

RemoteIterator类类似。

 其他内容可以直接输出,数据内容需转换:

Long timeStamp = s.getModificationTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = format.format(timeStamp);  
System.out.println("修改时间: " + date);;
//读取文件信息
FileStatus[] fileStatuses = fs.listStatus(hdfsPath);
for (FileStatus s : fileStatuses) {}
//读取目录下所有文件信息
RemoteIterator<LocatedFileStatus> remoteIterator = fs.listFiles(hdfsPath, true);
while (remoteIterator.hasNext()) {
	FileStatus s = remoteIterator.next();}

关系:FileStatus s = remoteIterator.next();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值