hdfs常用api(java)

1.下载文件到本地

public class HdfsUrlTest {

static{

//注册url java程序识别hdfsurl

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中的数据,最简单的方法是使用javaURL对象打开一个数据流,并从中读取数据

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

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

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

三种方法。

Getconf和geturiconf,newInstance

猜你喜欢

转载自www.cnblogs.com/lccyb/p/9488571.html