上传文件--copyfromLocalFile
@Test
public void hdfscopyfromlocal() throws IOException {
//上传文件
//src源文件即本地文件
//dit为目标文件
fs.copyFromLocalFile(new Path("E:/test.txt"),new Path("/"));
}
下载文件---copytoLocalFile
@Test
public void hdfscopytolocal() throws IOException {
//下载文件
fs.copyToLocalFile(new Path("/input"),new Path("E:/"));
}
其中我们可以通过代码修改副本参数
public void init() throws URISyntaxException, IOException, InterruptedException {
Configuration conf = new Configuration();
//代码设置副本参数
// conf.set("dfs.replication","2");
fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), conf, "root");
}
注意要点参数优先级 排序:
代码设置的值>用户自定义配置文件>服务器默认配置
删除文件或文件夹----delete
@Test
public void remove() throws IOException {
//删除文件 recursive:bool判断是否递归删除
fs.delete(new Path("/api_test"),true);
}
查看文件信息--listfiles
@Test
public void check(){
RemoteIterator<LocatedFileStatus> ite = null;
try {
ite = fs.listFiles(new Path("/"), true);
while (ite.hasNext()){
LocatedFileStatus status = ite.next();
//获取名字
String name = status.getPath().getName();
//获取文件长度
long len = status.getLen();
//获取权限名称
FsPermission permission = status.getPermission();
//获取分组
String group = status.getGroup();
//获取块信息
BlockLocation[] blockLocations = status.getBlockLocations();
System.out.println(name);
System.out.println(len);
System.out.println(permission);
System.out.println(group);
for (BlockLocation blockLocation : blockLocations) {
String[] hosts = blockLocation.getHosts();
for (String host : hosts) {
System.out.println(host);
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
判断是否是文件--filestatues,isfile
@Test
public void check_isfile() throws IOException {
FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
for (FileStatus fileStatus : fileStatuses) {
if (fileStatus.isFile()){
System.out.println("f:"+fileStatus.getPath().getName());
}
else{
System.out.println("d:"+fileStatus.getPath().getName());
}
}
}
总结:
通过对代码的运行进行验证是否是正确的