1.导入maven依赖
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client-api</artifactId>
<version>3.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client-runtime</artifactId>
<version>3.3.6</version>
</dependency>
2.配置Configuration信息
1)方法1:通过将hdfs的两个配置文件(hdfs-site.xml、core-site.xml)放到resources文件夹下后,新建Configuration的时候设置为true会自动读取,也可以通过conf.set(“配置”,“值”)来修改配置项
//创建配置,是否引用core-site.xml和hdfs-site.xml配置文件,true是引用
Configuration conf = new Configuration(true);
//创建文件连接流,指定namenode、conf和连接的用户名
FileSystem fs = FileSystem.get(new URI("mycluster"),conf,"hadoop");
2)方法2:将Configuration设置为false,不加载默认配置文件,直接指定namenode对应的ip和端口如:hdfs://192.168.132.101:8081替换mycluster
Configuration conf = new Configuration(false);
FileSystem fs = FileSystem.get(new URI("hdfs://192.168.132.101:8081"),conf,"hadoop");
3.hdfs集成springboot基本命令
1)判断文件是否存在
fs.exists(new Path("/out.txt"))
2)创建文件夹
fs.mkdirs(new Path("/dir1"));
3)创建文件夹并设置权限为文件所有者可读可写,文件所有组可读可写,其他人可读
fs.mkdirs(new Path("/dir2"),new FsPermission(FsAction.READ_WRITE,FsAction.READ_WRITE,FsAction.READ));
4)删除文件夹
fs.delete(new Path("/dir1"),true);
5)创建文件并输入文本
如果文件存在,默认会覆盖, 可以通过第二个参数进行控制。第三个参数可以控制使用缓冲区的大小
FSDataOutputStream out = fs.create(new Path("/test.txt"),true, 4096);
out.write("hello hadoop!".getBytes());
out.flush();
out.close();
6)读取文本
FSDataInputStream inputStream = fs.open(new Path("/test.txt"));
byte[] contextBytes = new byte[1024];
inputStream.read(contextBytes);
String context = new String(contextBytes,"utf-8");
System.out.println(context);
7)文件重命名
boolean result = fs.rename(new Path("/test.txt"), new Path("/testnew.txt"));
8)上传文件
fs.copyFromLocalFile(new Path("./data/hello.txt"), new Path("/hdfshello.txt"));
9)下载文件
fs.copyToLocalFile(false, new Path("/hdfshello.txt"), new Path("./data/testdata.txt"), true);
10)输出所有列表所有文件和文件夹信息
FileStatus[] statuses = fs.listStatus(new Path("/"));
for (FileStatus fileStatus : statuses) {
System.out.println(fileStatus.toString());
}
11)递归查询目录所有文件信息,比listStatus多了文本大小,副本系数,块大小信息
RemoteIterator<LocatedFileStatus> files = fs.listFiles(new Path("/"), true);
while (files.hasNext()) {
System.out.println(files.next());
}
12)查询文件块信息
FileStatus fileStatus = fs.getFileStatus(new Path("/user/master01/data.txt"));
BlockLocation[] blocks = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
for (BlockLocation block : blocks) {
System.out.println(block);
}
13)查询文件块信息并跳转读取
FileStatus fileStatus = fs.getFileStatus(new Path("/user/master01/data.txt"));
BlockLocation[] blocks = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
FSDataInputStream input = fs.open(new Path("/user/master01/data.txt"));
input.seek(blocks[1].getOffset());
//input.seek(0)是让指针回到开始
System.out.println(input.readLine());