hadoop学习之HDFS(2.8):hdfs的javaAPI使用及示例

来源:互联网 发布:重启oracle数据库 编辑:程序博客网 时间:2024/06/06 12:07

安装好hadoop后,可以在命令行启动客户端,通过命令行来操作hdfs,如:

$ bin/hadoop fs -ls /       //查看根目录下的内容
$ bin/hadoop fs -mkdir /user   //在根目录下创建user文件夹
$ bin/hadoop fs -put /root/words.txt /user/words.txt    //将本地文件上传到hdfs上。

对于实际开发,hadoop也提供了一套完善的,关于hdfs操作的javaAPI,下面简要介绍:

hadoop提供的jar包在:path_to/hadoop/share/hadoop下,里面有很多目录,包括公共jar包common,hdfs的jar包hdfs,mr的jar包mapreduce。

那么,在操作hdfs时,我们就要导入common包和hdfs包。

1,导入common文件夹下的hadoop-common-2.7.2.jar,同时导入common/lib下的所有jar包(因为可能存在依赖关系)。

2,导入hdfs文件夹下的hadoop-hdfs-2.7.2.jar,同时导入hdfs/lib下的所有jar包(同样因为可能存在依赖关系)。

下面列出常用操作的java代码:

package com.jimmy.hdfs;import java.io.IOException;import java.util.Iterator;import java.util.Map.Entry;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FileStatus;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.LocatedFileStatus;import org.apache.hadoop.fs.Path;import org.apache.hadoop.fs.RemoteIterator;import org.junit.Before;import org.junit.Test;public class HdfsClientDemo {Configuration conf = null;FileSystem fs = null;@Beforepublic void init() throws Exception{conf = new Configuration();conf.set("fs.defaultFS", "hdfs://node1:9000");fs = FileSystem.get(conf);}/** * 测试上传 * @throws Exception */@Testpublic void testUpload() throws Exception{fs.copyFromLocalFile(new Path("E:/hadoopTestData/words2.txt"), new Path("/user/root/input_wordcount/"));fs.close();}/** * 测试打印conf参数列表 */@Testpublic void testConf(){Iterator<Entry<String, String>> iterator = conf.iterator();while (iterator.hasNext()) {Entry<String, String> next = iterator.next();System.out.println(next.getKey()+" : "+next.getValue());}}/** * 测试创建文件夹 * @throws Exception  * @throws   */@Testpublic void testMKdir() throws  Exception{boolean mkdirs = fs.mkdirs(new Path("/user/root/test"));System.out.println(mkdirs);}/** * 测试删除文件/文件夹 * @throws Exception  * @throws   */@Testpublic void testDelete() throws  Exception{boolean deleteOnExit = fs.deleteOnExit(new Path("/user/root/input_wordcount/words3"));System.out.println(deleteOnExit);}/** * 测试递归查询指定目录下所有子文件夹中的文件 * @throws IOException  * @throws IllegalArgumentException  * @throws   */@Testpublic void testLS() throws Exception {RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);while(listFiles.hasNext()){LocatedFileStatus next = listFiles.next();System.out.println("name:"+next.getPath().getName());System.out.println("path:"+next.getPath());System.out.println("blcSize: "+next.getBlockSize());System.out.println("owner: "+next.getOwner());System.out.println("----------------");}}/** * 测试显示一个路径下的内容 */@Testpublic void testLS2() throws Exception{FileStatus[] listStatus = fs.listStatus(new Path("/"));for(FileStatus fileStatus:listStatus){System.out.println(fileStatus.getPath().getName());System.out.println(fileStatus.isFile()?"file":"dir");}}}


0 0