Java操作
# Java 操作
# HDFS 文件上传
//获取配置对象
Configuration configuration = new Configuration();
//设置配置 将默认分块设置为2
configuration.set("dfs.replication","2");
//新建HDFS对象
FileSystem fileSystem = FileSystem.get(URI.create("hdfs://hadoop102:8020"), configuration, "atguigu");
//操作集群
fileSystem.copyFromLocalFile(new Path("D:\\图\\QQ图片20190517141148.jpg"),new Path("/"));
//关闭资源
fileSystem.close();
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- get (URI.crate ("hdfs://hadoop 地址"),new Configuation (), 集群用户名); 获取 HDFS 操作对象
- copyFromLocalFile (new Path ("本地路径"),new Path (集群路径)); 上传文件到 HDFS
# HDFS 下载到本地
fileSystem.copyToLocalFile(
new Path("/QQ图片20190517141148.jpg"),
new Path("d:/images")
);
1
2
3
4
2
3
4
# HDFS 追加
FSDataOutputStream append = fileSystem.append(
new Path("1.txt")
);
//写入流
append.write("testApi".getBytes(StandardCharsets.UTF_8));
//关闭流
IOUtils.closeStream(append);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# ls
//ls操作 返回数组
FileStatus[] fileStatuses = fileSystem.listStatus(new Path("/"));
for (FileStatus fileStatus : fileStatuses) {
//获取文件对象路径
System.out.println(fileStatus.getPath());
//获取文件所属者
System.out.println(fileStatus.getOwner());
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# listFiles
//获取当前所有文件的迭代器 无论是文件夹还是文件 true返回一个迭代器
RemoteIterator<LocatedFileStatus> locatedFileStatusRemoteIterator = fileSystem.listFiles(
new Path("/"),
true);
while (locatedFileStatusRemoteIterator.hasNext()) {
LocatedFileStatus fileStatus = locatedFileStatusRemoteIterator.next();
System.out.println(fileStatus.getPath());
//获取当前文件的块 返回数组
BlockLocation[] blockLocations = fileStatus.getBlockLocations();
for (int i = 0; i < blockLocations.length; i++) {
System.out.println("第" + i + "块");
//获取当前文件 每个块存储的集群情况
String[] hosts = blockLocations[i].getHosts();
for (String host : hosts) {
System.out.print(host + " ");
}
System.out.println();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 移动或重命名
//重命名或者移动文件
fileSystem.rename(new Path("/QQ图片20190517141148.jpg"),new Path("/test/233.jpg"));
1
2
2
编辑 (opens new window)
上次更新: 2023/12/06, 01:31:48