JavaAPI操作HDFS文本系统
window下用到的hadoop版本:
创建项目
使用idea创建的项目
org.apache.hadoop
hadoop-client
2.6.4
操作JavaAPI
1.初始化方式一操作
注意:出现错误请查看hadoop系统六错误解决方案
private FileSystem fs;
private Configuration c;
@Before
public void init() throws Exception {
c = new Configuration();
//方式一 设置地址,传递配置,在vm options中设置-DHADOOP_USER_NAME=hadoop
c.set("fs.defaultFS", "hdfs://mini06:9000");
//拿到一个文件系统操作客户端实例对象
fs = FileSystem.get(c);
}
2.初始化方式二操作 推荐
private FileSystem fs;
private Configuration c;
@Before
public void init() throws Exception {
c = new Configuration();
//方式二 传递用户与文件系统
/**
* URI uri, hdfs的地址
* Configuration conf, 客户端配置对象
* String user 指定linux上运行的用户名称
*/
fs = FileSystem.get(new URI("hdfs://mini06:9000"), c, "hadoop");
}
3.文件上传
//从本地上传文件到hadoop hdfs文件系统的根目录下
@Test
public void upload() throws IOException {
/**
* 将文件上传到fdhs
* 参数一:本地文件路径
* 参数二:fdhs文件目录
*/
f.copyFromLocalFile(new Path("c:/1.png"),new Path("/"));
f.close();
}
4.下载文件
//从hadoop hdfs下载文件到本地
@Test
public void testDonwload() throws IOException {
/**
* Path src, 下载的地址
* Path dst 存放下载文件的地址
*/
f.copyToLocalFile(new Path("/1.png"),new Path("d:/2.png"));
f.close();
}
5.获取客户端所有配置信息并打印
//获取客户端所有的配置信息
@Test
public void testGetConf(){
Iterator<>> it = c.iterator();
while(it.hasNext()){
Map.Entry conf = it.next();
System.out.println(conf.getKey()+":"+conf.getValue());
}
}
6.创建目录
默认就是递归创建目录
//创建目录
@Test
public void testMkdir() throws IOException {
boolean mkdirs = f.mkdirs(new Path("/abc/def"));
System.out.println("是否创建成功"+mkdirs);
}
7.删除文件
//删除文件
@Test
public void testDelete() throws IOException {
/**
* 参数一:删除的路径
* 参数二:要不要递归删除
* 返回:是否删除成功
*/
boolean delete = f.delete(new Path("/1.png"), false);
System.out.println("是否删除成功:"+delete);
}
8.递归列出文件下文件与子文件
//递归列出文件下文件与子文件
@Test
public void testTrss() throws IOException {
/**
* 参数一:路径
* 参数二:是否递归查询
* 返回:返回迭代器
*/
RemoteIterator listFiles = f.listFiles(new Path("/"),true);
while(listFiles.hasNext()){
LocatedFileStatus fs = listFiles.next();
System.out.println("blockSize:" + fs.getBlockSize());
System.out.println("owner:" + fs.getOwner());
System.out.println("replication:" + fs.getReplication());
System.out.println("permission:" + fs.getPermission());
System.out.println("path:" + fs.getPath());
//获取某一个文件的块信息
BlockLocation[] blockLocations = fs.getBlockLocations();
for (BlockLocation b:blockLocations){
//获取某一个文件分块后的起始位置
System.out.println("offset:"+b.getOffset());
//获取每一个块的大小
System.out.println("block length:"+b.getLength());
String[] datanodes = b.getHosts();
for (String node:datanodes){
System.out.println("datanodes:"+node);
}
}
System.out.println("========================================================");
}
}
9.读取一级目录
//读取一级目录
@Test
public void testLs2() throws IOException {
FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
for (FileStatus f : fileStatuses) {
System.out.print(f.getPath().getName());
System.out.println(f.isFile() ? "====>file:" : "====>directory");
}
}