您的位置:首页 > 编程语言 > Java开发

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

2016-11-23 11:48 591 查看
安装好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;
@Before
public void init() throws Exception{
conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://node1:9000");
fs = FileSystem.get(conf);
}
/**
* 测试上传
* @throws Exception
*/
@Test
public void testUpload() throws Exception{
fs.copyFromLocalFile(new Path("E:/hadoopTestData/words2.txt"), new Path("/user/root/input_wordcount/"));
fs.close();
}
/**
* 测试打印conf参数列表
*/
@Test
public 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
*/
@Test
public void testMKdir() throws  Exception{
boolean mkdirs = fs.mkdirs(new Path("/user/root/test"));
System.out.println(mkdirs);
}
/**
* 测试删除文件/文件夹
* @throws Exception
* @throws
*/
@Test
public void testDelete() throws  Exception{
boolean deleteOnExit = fs.deleteOnExit(new Path("/user/root/input_wordcount/words3"));
System.out.println(deleteOnExit);
}
/**
* 测试递归查询指定目录下所有子文件夹中的文件
* @throws IOException
* @throws IllegalArgumentException
* @throws
*/
@Test
public 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("----------------");
}
}
/**
* 测试显示一个路径下的内容
*/
@Test
public 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");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: