HDFS–api操作(java)
引入maven
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>2.7.2</version>
</dependency>
</dependenies>
src/resources目录下,放入log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
API
获得FileSystem
private FileSystem fs;
@Before
public void testMkdirs() throws IOException, InterruptedException, URISyntaxException{
// 1 获取文件系统
Configuration configuration = new Configuration();
// 配置在集群上运行
// configuration.set("fs.defaultFS", "hdfs://ip:9000");
// FileSystem fs = FileSystem.get(configuration);
fs = FileSystem.get(new URI("hdfs://ip:9000"), configuration, "user");
}
API详解
@Test
public void apiTest() throws Exception {
// 创建目录
fs.mkdirs(new Path("/testFolder"));
// 上传文件
fs.copyFromLocalFile(new Path("e:/test.txt"), new Path("/testFile.txt"));
// 文件下载 参数详解
// boolean delSrc 指是否将原文件删除
// Path src 指要下载的文件路径
// Path dst 指将文件下载到的路径
// boolean useRawLocalFileSystem 是否开启文件校验
fs.copyToLocalFile(false, new Path("/testFile.txt"), new Path("e:/test2.txt"), true);
// 文件夹删除
fs.delete(new Path("/testFolder"), true);
// 修改文件名称
fs.rename(new Path("/testFile.txt"), new Path("/test2.txt"));
}
文件详情查看
遍历文件夹,得到文件,并输出详情
@Test
public void fileDetails() throws Exception {
// 获取文件详情
RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
while(listFiles.hasNext()){
LocatedFileStatus status = listFiles.next();
// 输出详情
// 文件名称
System.out.println(status.getPath().getName());
// 长度
System.out.println(status.getLen());
// 权限
System.out.println(status.getPermission());
// 分组
System.out.println(status.getGroup());
// 获取存储的块信息
BlockLocation[] blockLocations = status.getBlockLocations();
for (BlockLocation blockLocation : blockLocations) {
// 获取块存储的主机节点
String[] hosts = blockLocation.getHosts();
for (String host : hosts) {
System.out.println(host);
}
}
System.out.println("-----------分割线----------");
}
}
文件和文件夹的判断
@Test
public void fileOrDirectory() throws Exception {
FileStatus[] listStatus = fs.listStatus(new Path("/"));
for (FileStatus fileStatus : listStatus) {
// 如果是文件
if (fileStatus.isFile()) {
System.out.println("f:"+fileStatus.getPath().getName());
}else {
System.out.println("d:"+fileStatus.getPath().getName());
}
}
}
最后记得关闭文件系统
@After
public void fsClose() throws Exception {
fs.close();
}
HDFS的I/O流
import org.apache.hadoop.io.IOUtils;
@Test
public void putFileToHDFS() throws Exception{
// 创建输入流
FileInputStream fis = new FileInputStream(new File("e:/banhua.txt"));
// 获取输出流
FSDataOutputStream fos = fs.create(new Path("/banhua.txt"));
// 流对拷
IOUtils.copyBytes(fis, fos, configuration);
// 关闭资源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
}
Test
public void getFileFromHDFS() throws IOException, InterruptedException, URISyntaxException{
// 获取输入流
FSDataInputStream fis = fs.open(new Path("/banhua.txt"));
// 获取输出流
FileOutputStream fos = new FileOutputStream(new File("e:/banhua.txt"));
// 流的对拷
IOUtils.copyBytes(fis, fos, configuration);
// 关闭资源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
}
定位文件读取
@Test
public void readFileSeek1() throws IOException, InterruptedException, URISyntaxException{
// 获取输入流
FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz"));
// 创建输出流
FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.2.tar.gz.part1"));
// 流的拷贝
byte[] buf = new byte[1024];
for(int i =0 ; i < 1024 * 128; i++){
fis.read(buf);
fos.write(buf);
}
// 关闭资源
IOUtils.closeStream(fis);
IOUtils.closeStream(fos);
}
@Test
public void readFileSeek2() throws IOException, InterruptedException, URISyntaxException{
// 打开输入流
FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz"));
// 定位输入数据位置
fis.seek(1024*1024*128);
// 创建输出流
FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.2.tar.gz.part2"));
// 流的对拷
IOUtils.copyBytes(fis, fos, configuration);
// 关闭资源
IOUtils.closeStream(fis);
IOUtils.closeStream(fos);
}
合并文件
在Window命令窗口中进入到目录E:\,然后执行如下命令,对数据进行合并
type hadoop-2.7.2.tar.gz.part2 >> hadoop-2.7.2.tar.gz.part1
合并完成后,将hadoop-2.7.2.tar.gz.part1重新命名为hadoop-2.7.2.tar.gz。解压发现该tar包非常完整。
HDFS读写流程
- client–>Namenode,申请上传文件:发起申请,Namenode判断请求是否合法,是否有该权限上传数据;
- client将要上传的文件进行逻辑切法,(逻辑切分:例如200Mb的文件,画一条线,分别为78和122mb,但该文件并没有分为2个文件);
- client请求上传第一个block(如78Mb的文件),Namenode返回datanode的list;表示采用这些节点存储数据;返回的节点个数是你请求上传时,请求的存储数集的数量;例如返回d1,d2,d3
- client创建输出流,与d1请求建立通道,d1向d2请求建立通道,d2向d3请求建立通道,d3向d2应答成功,d2向d1应答成功,d1向client应答成功;
- client收到d1应答成功,表明通道全部建立成功,开始向d1传输packet;d1本地落盘的同时,向d2传输数据,d2同理;
- d3数据完成,向d2返回成功,d2自己落盘完成并收到d3的成功时,向d1发送成功信息,d1同理
- 开始传输第二块数据;过程相同;
- 数据传递完毕,client关闭输出流,向namenode传递成功信息,namenode收到成功信息,更新元数据(metadata),
注意事项:
- 文件切分两次的,namenode给的datanode的list可能完全不一样;上传至hdfs的过程中,已经完成了物理切分,故而是两个独立的事件了;
- 过程中如果失败了:
- 建立通道的过程中失败:上传失败,抛出异常
- 传输数据中失败:
- 上述案例,client与d1传输时失败,上传失败,抛出异常
- d1与d2失败,上传依然进行,返回成功信号;副本数为1;因设置的备份数大于1,启动自动备份的,将在其他datanode上进行备份
读
写
- 客户端通过Distributed FileSystem向NameNode请求下载文件,NameNode通过查询元数据,找到文件块所在的DataNode地址。
- 挑选一台DataNode(就近原则,然后随机)服务器,请求读取数据。
- DataNode开始传输数据给客户端(从磁盘里面读取数据输入流,以Packet为单位来做校验)。
- 客户端以Packet为单位接收,先在本地缓存,然后写入目标文件。