hdfs api java_hdfs常用api(java)

1.下载文件到本地

public class HdfsUrlTest {

static{

//注册url让java程序识别hdfs的url

URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());

}

public static void main(String[] args) {

InputStream in = null;

OutputStream out = null;

try {

String file = "hdfs://hadoop-yarn.test.com:8020/user/testi/conf/core-site.xml";

URL fileUrl = new URL(file);

in = fileUrl.openStream();

out = new FileOutputStream(new File("d:/core-site.xml"));

//下载文件到本地

IOUtils.copyBytes(in,out,4096, false);

} catch (Exception e) {

e.printStackTrace();

}finally{

IOUtils.closeStream(in);}}}

2.查看集群信息

public static void cluserStatus() throws Exception{

FileSystem fs = HdfsUtil.getFs();

DistributedFileSystem dfs  = (DistributedFileSystem)fs;

FsStatus fss = dfs.getStatus();

DatanodeInfo[] datanodeInfos = dfs.getDataNodeStats();

for(DatanodeInfo datanodeinfo : datanodeInfos){

System.out.println(datanodeinfo.getHostName());}}

3.创建一个文件夹

public void testHDFSMkdir() throws Exception{

String hdfsUrl = "hdfs://192.168.10.11:8020";

Configuration conf= new Configuration();

FileSystem fs = FileSystem.get(URI.create(hdfsUrl),conf);

Path path = new Path("/bigdata");

fs.mkdirs(path);}

4.创建一个文件

public void testCreateFile() throws Exception{

String hdfsUrl = "hdfs://192.168.10.11:8020";

Configuration conf= new Configuration();

FileSystem fs = FileSystem.get(URI.create(hdfsUrl),conf);

Path path = new Path("/bigdata/a.txt");

FSDataOutputStream out = fs.create(path);

out.write("hello hadoop".getBytes());}

5.文件重命名

public void testRenameFile() throws Exception{

String hdfsUrl = "hdfs://192.168.10.11:8020";

Configuration conf= new Configuration();

FileSystem fs = FileSystem.get(URI.create(hdfsUrl),conf);

Path path = new Path("/bigdata/a.txt");

Path newPath = new Path("/bigdata/b.txt");

System.out.println(fs.rename(path, newPath));}

6.上传文件

public static void write() throws Exception{

FileSystem fs = HdfsUtil.getFs();

OutputStream outStream = fs.create(new Path("/user/lcc/conf/put-core-site.xml"));

FileInputStream inStream = new FileInputStream(new File("d:/core-site.xml"));

IOUtils.copyBytes(inStream, outStream, 4096, true);}

Hadoop程序想读取hdfs中的数据,最简单的方法是使用java的URL对象打开一个数据流,并从中读取数据。

需要一个fsUrlStreamHandlerFactory实例调用set过的一个URL,这种方法java虚拟机只能调用一次,缺点是如果程序的其他部分也设置了这个,会导致无法再从hadoop中读取数据。

新方法,需要使用filesystem的api打开一个文件的输入流。

文件在hadoop文件系统中被视为一个hadoop path对象,把一个文件夹或文件路径看做为一个hadoop文件系统的URL。

三种方法。

Get(conf)和get(uri,conf),newInstance

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值