HDFS API
package com.xiaoqiu;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
public class HdfsClient {
private FileSystem fs;
@Before
public void init() throws URISyntaxException, IOException, InterruptedException {
//设置ip
URI uri = new URI("hdfs://hadoop104:8020");
//获取配置
Configuration configuration = new Configuration();
//可以设置副本数量
configuration.set("dfs.replication", "3");
//设置用户
String user = "hadoop";
//获取文件系统
fs = FileSystem.get(uri, configuration, user);
}
@After
public void close() throws IOException {
//关闭资源
fs.close();
}
//创建文件夹
@Test
public void testMkdir() throws IOException {
fs.mkdirs(new Path("/testMkdir"));
}
//上传文件(从windows上传到hdfs)
@Test
public void upload() throws IOException {
//参数:是否删除原数据,是否允许覆盖,源数据windows路径,目标hdfs路径
fs.copyFromLocalFile(false, false, new Path("F:\share\phone_data.txt"), new Path("/testMkdir/phone_data.txt"));
}
//下载文件(从hdfs下载到windows)
@Test
public void download() throws IOException {
//参数:是否删除原数据,原数据hdfs路径,目标windows路径,是否开启本地数据校验
fs.copyToLocalFile(false,new Path("/testMkdir/phone_data.txt"),new Path("F:\share\phone_data1.txt"),true);
}
//删除
@Test
public void rm() throws IOException {
//参数:要删除的路径,是否递归(与rm作用一致)
fs.delete(new Path("/sanguo/shuguo.txt"),true);
}
//文件更名与移动
@Test
public void mv() throws IOException {
//参数:原文件路径,目标文件路径(与mv作用一致)
fs.rename(new Path("/sanguo/weiguo.txt"),new Path("/sanguo/wei.txt"));
}
//获取文件详情
@Test
public void fileDetail() throws IOException {
//获取所有文件信息
RemoteIterator listFiles = fs.listFiles(new Path("/"), true);
while (listFiles.hasNext()){
LocatedFileStatus status = listFiles.next();
System.out.println(
status.getPermission()+"t"
+status.getOwner()+"t"
+status.getGroup()+"t"
+status.getLen()+"t"
+status.getModificationTime()+"t"
+status.getReplication()+"t"
+status.getBlockSize()+"t"
+Arrays.toString(status.getBlockLocations()) +"t"
+status.getPath().getName()
);
}
}
//判断是文件还是文件夹
@Test
public void file() throws IOException {
FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
for (FileStatus fileStatus : fileStatuses) {
if (fileStatus.isFile()){
System.out.println("文件"+fileStatus.getPath().getName());
}else {
System.out.println("目录"+fileStatus.getPath().getName());
}
}
}
}