首页 > 编程 > Java > 正文

JAVA操作HDFS案例的简单实现

2019-11-26 11:41:40
字体:
来源:转载
供稿:网友

本文介绍了JAVA操作HDFS案例的简单实现,分享给大家,也给自己做个笔记

Jar包引入,pom.xml:

<dependency>  <groupId>org.apache.hadoop</groupId>  <artifactId>hadoop-common</artifactId>  <version>2.8.0</version> </dependency> <dependency>  <groupId>org.apache.hadoop</groupId>  <artifactId>hadoop-hdfs</artifactId>  <version>2.8.0</version> </dependency> 

将本地文件上传到hdfs服务器:

/**  * 上传文件到hdfs上  */ @Test public void upload() throws IOException {   Configuration conf = new Configuration();   conf.set("fs.defaultFS","hdfs://hzq:9000");   FileSystem fs = FileSystem.get(conf);   fs.copyFromLocalFile(new Path("/home/hzq/jdk1.8.tar.gz"),new Path("/demo")); } 

解析:

在开发中我没有引入“core-site.xml”配置文件,所以在本地调用时使用conf进行配置“conf.set("fs.defaultFS","hdfs://hzq:9000");“,下面雷同。

将hdfs上文件下载到本地:

/**  * 将hdfs上文件下载到本地  */ @Test public void download() throws IOException {   Configuration conf = new Configuration();   conf.set("fs.defaultFS","hdfs://hzq:9000");   FileSystem fs = FileSystem.newInstance(conf);   fs.copyToLocalFile(new Path("/java/jdk1.8.tar.gz"),new Path("/home/hzq/")); } 

删除hdfs上指定文件:

/**  * 删除hdfs上的文件  * @throws IOException  */ @Test public void removeFile() throws IOException {   Configuration conf = new Configuration();   conf.set("fs.defaultFS","hdfs://hzq:9000");   FileSystem fs = FileSystem.newInstance(conf);   fs.delete(new Path("/demo/jdk1.8.tar.gz"),true); } 

在hdfs上创建文件夹:

/**  * 在hdfs更目录下面创建test1文件夹  * @throws IOException  */ @Test public void mkdir() throws IOException {   Configuration conf = new Configuration();   conf.set("fs.defaultFS","hdfs://hzq:9000");   FileSystem fs = FileSystem.newInstance(conf);   fs.mkdirs(new Path("/test1")); } 

列出hdfs上所有的文件或文件夹:

@Test   public void listFiles() throws IOException {     Configuration conf = new Configuration();     conf.set("fs.defaultFS","hdfs://hzq:9000");     FileSystem fs = FileSystem.newInstance(conf);     // true 表示递归查找 false 不进行递归查找     RemoteIterator<LocatedFileStatus> iterator = fs.listFiles(new Path("/"), true);     while (iterator.hasNext()){       LocatedFileStatus next = iterator.next();       System.out.println(next.getPath());     }     System.out.println("----------------------------------------------------------");     FileStatus[] fileStatuses = fs.listStatus(new Path("/"));     for (int i = 0; i < fileStatuses.length; i++) {       FileStatus fileStatus = fileStatuses[i];       System.out.println(fileStatus.getPath());     }   } 

运行结果:

                                    

结果分析:

“listFiles“列出的是hdfs上所有文件的路径,不包括文件夹。根据你的设置,支持递归查找。

  ”listStatus“列出的是所有的文件和文件夹,不支持递归查找。如许递归,需要自己实现。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表