源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JAVA操作HDFS案例的简单实现

  • 时间:2021-09-09 18:55 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JAVA操作HDFS案例的简单实现
本文介绍了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()); 
    } 
  } 
运行结果: [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100111_0_17358.jpg[/img]                                      [b]结果分析: [/b] “listFiles“列出的是hdfs上所有文件的路径,不包括文件夹。根据你的设置,支持递归查找。   ”listStatus“列出的是所有的文件和文件夹,不支持递归查找。如许递归,需要自己实现。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部