HDFS(分布式存储)_Hadoop核心_002-----------通过javaAPI的方式操作HDFS

10-HDFS的API操作-配置Window系统下的Hadoop

 

 

 

 ==================================================================================================

11-HDFS的API操作-获取FileSystem方式1

1.9. HDFS 的 API 操作
1.9.1. 导入 Maven 依赖

----------------------------------------------------------------------------------------------------------------------------------------------------------

1.9.2. 概述
在 Java 中操作 HDFS, 主要涉及以下 Class:

Configuration

该类的对象封转了客户端或者服务器的配置
FileSystem

该类的对象是一个文件系统对象, 可以用该对象的一些方法来对文件进行操作, 通过 FileSystem 的静态方法 get 获得该对象


FileSystem fs = FileSystem.get(conf)
get 方法从 conf 中的一个参数 fs.defaultFS 的配置值判断具体是什么类型的文件系统
如果我们的代码中没有指定 fs.defaultFS, 并且工程 ClassPath 下也没有给定相应的配置, conf 中的默认值就来自于 Hadoop 的 Jar 包中的 core-default.xml
默认值为 file:///, 则获取的不是一个 DistributedFileSystem 的实例, 而是一个本地文件系统的客户端对象


1.9.3. 获取 FileSystem 的几种方式
第一种方式

@Test
public void getFileSystem() throws URISyntaxException, IOException {
Configuration configuration = new Configuration();
FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), configuration);
System.out.println(fileSystem.toString());
}
第二种方式

@Test
public void getFileSystem2() throws URISyntaxException, IOException {
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://192.168.52.250:8020");
FileSystem fileSystem = FileSystem.get(new URI("/"), configuration);
System.out.println(fileSystem.toString());
}
第三种方式

@Test
public void getFileSystem3() throws URISyntaxException, IOException {
Configuration configuration = new Configuration();
FileSystem fileSystem = FileSystem.newInstance(new URI("hdfs://192.168.52.250:8020"), configuration);
System.out.println(fileSystem.toString());
}
第四种方式

@Test
public void getFileSystem4() throws Exception{
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://192.168.52.250:8020");
FileSystem fileSystem = FileSystem.newInstance(configuration);
System.out.println(fileSystem.toString());
}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 pom.xml

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.nantian</groupId>
<artifactId>hdfs_api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<repositories>
<repository>
<id>cloudera</id>
<!-- 指定jar包的下载地址 -->
<url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
<version>1.8</version>
<scope>system</scope>
<systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>3.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs-client</artifactId>
<version>3.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

--------------------------------------------------------------------------------------------------------------------------------

log4j.properties

log4j.rootLogger=WARN, Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=(%r ms) [%t] %-5p: %c#%M %x: %m%n

log4j.logger.com.genuitec.eclipse.sqlexplorer=DEBUG
log4j.logger.org.apache=WARN
log4j.logger.net.sf.hibernate=WARN

-----------------------------------------------------------------------------------------------------------

HdfsApiStudy.java

package com.hdfs;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.junit.Test;

public class HdfsApiStudy {

//获取文件系统的第四种方式
@Test
public void getFileSystem4() throws Exception {
FileSystem fileSystem=FileSystem.newInstance(new URI("hdfs://node01:8020"),new Configuration());
System.out.println(fileSystem.toString());
}

//获取文件系统的第三种方式
@Test
public void getFileSystem3() throws Exception {
Configuration configuration=new Configuration();
configuration.set("fs.defaultFs", "hdfs://node01:8020");

FileSystem fileSystem=FileSystem.newInstance(configuration);
System.out.println(fileSystem.toString());

}

//获取文件系统的第二种方式
@Test
public void getFileSystem2() throws IOException, URISyntaxException {
FileSystem fileSystem=FileSystem.get(new URI("hdfs://node01:8020"),new Configuration());
System.out.println(fileSystem.toString());

}
//获取文件系统的第一种方式
@Test
public void getFileSystem1() throws IOException {
//获取Configuration对象
Configuration configuration = new Configuration();
//设置Configuration对象,设置的目的是来指定我们要操作的文件系统
//set有两个参数fs.defaultFS为固定值,"hdfs://192.168.187.100:8020"表示要操作的文件系统
//hdfs://192.168.187.100:8020;hdfs代表操作的是分布式文件系统,192.168.187.100元数据节点ip
configuration.set("fs.defaultFS", "hdfs://192.168.187.100:8020");
//获取我们指定的文件系统,获取FileSystem就相当于获取了主节点中所有的元数据信息
FileSystem fileSystem=FileSystem.get(configuration);
System.out.println("fifleSystem:"+fileSystem);
//fifleSystem:DFS[DFSClient[clientName=DFSClient_NONMAPREDUCE_1273879488_1, ugi=xjj13 (auth:SIMPLE)]];说明已经建立了连接
}




}

-------------------------------------------------------------------------------------------------------------------------------------

运行结果:

 =================================================================================================================

13-HDFS的API操作-获取文件列表信息

//获取目录下所有的文件信息
@Test
public void getListFiles() throws Exception {
//1.获取Filesystem
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"),new Configuration());
//2.获取指定目录下的所有文件信息
//new Path("/"):/代表根目录 true:代表递归遍历
RemoteIterator<LocatedFileStatus> iterator = fileSystem.listFiles(new Path("/"), true);
//3.遍历迭代器
while (iterator.hasNext()) {
//获取每一个文件的详细信息
LocatedFileStatus fileStatus = iterator.next();
//获取每一个文件的存储路径
System.out.println("文件存储路径:"+fileStatus.getClass()+";文件名:"+fileStatus.getPath().getName());

//获取文件的block存储信息
BlockLocation[] blockLocations = fileStatus.getBlockLocations();
//打印每个文件的block数
System.out.println("每个文件的block数:"+blockLocations.length);
//打印每一个block副本的存储位置
for (BlockLocation blockLocation : blockLocations) {
String[] hosts = blockLocation.getHosts();
for (String host : hosts) {
System.out.println("每一个block副本的存储位置:"+host);
}
}


}
}

--------------------------------------------------------------------------------------------------

执行结果

 =======================================================================================================================

 14-HDFS的API操作-创建文件和文件夹

//在hdfs上创建文件夹和创建文件
@Test
public void mkdirsTest() throws Exception {
//1.获取FileSystem对象
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"),new Configuration());
//2.创建文件夹
fileSystem.mkdirs(new Path("/app/test/hello"));
//3.创建文件
fileSystem.create(new Path("/a.txt"));
}

运行结果:

 

 ===============================================================================================================

15-HDFS的API操作-文件的上传和下载

//实现文件的下载:方式2
@Test
public void downloadFileTest2() throws Exception{
//1.获取FileSystem对象
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"),new Configuration());
//2.调用方法直接实现文件的下载
fileSystem.copyToLocalFile(new Path("/a.txt"), new Path("D://a.txt"));
fileSystem.close();
}

//实现文件的下载:方式1
@Test
public void downloadFileTest() throws Exception{
//1.获取FileSystem对象
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"),new Configuration());
//2.获取Hdfs文件的输入流
FSDataInputStream inputStream = fileSystem.open(new Path("/a.txt"));
//3.获取本地文件的输出流
FileOutputStream outputStream = new FileOutputStream(new File("D://a.txt"));
//4.实现文件的复制
IOUtils.copy(inputStream, outputStream);
//5.关闭流
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
fileSystem.close();

}

 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//实现文件的上传
@Test
public void uploadFileTest() throws Exception{
//1.获取FileSystem对象
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"),new Configuration());
//2.调用方法实现问价的上传
fileSystem.copyFromLocalFile(new Path("D://hello.txt"), new Path("/hello.txt"));

fileSystem.close();
}

 ============================================================================================================

16-HDFS的API操作-访问权限问题

 

 

 

 

 说明:

刚才设置的权限对我毫无影响

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1).先停止集群

 停止yarn集群

 2)修改

 3)重新启动集群

 

 

 

 

 报错:

org.apache.hadoop.security.AccessControlException: Permission denied: user=xjj13, access=READ, inode="/timer.txt":root:supergroup:----------

 

//实现文件的下载:方式2
@Test
public void downloadFileTest2() throws Exception{
//1.获取FileSystem对象
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"),new Configuration(),"root");//伪造用户
//2.调用方法直接实现文件的下载
fileSystem.copyToLocalFile(new Path("/timer.txt"), new Path("D://timer3.txt"));
fileSystem.close();
}

 注意:

首先要保证配置文件的总权限要打开

有两种方式去读写文件:

1.-chmod

2.伪造用户

=============================================================================================

 17-HDFS的API操作-小文件的合并

 

//小文件的合并
@Test
public void mergeFileTest() throws Exception {
//1.获取FileSystem对象
FileSystem fileSystem = FileSystem.get(new URI("hdfs://node01:8020"),new Configuration(),"root");//伪造用户
//2.在hdfs创建一个大文件
FSDataOutputStream outputStream = fileSystem.create(new Path("/bigFile.txt"));
//3.获取本地的文件系统
LocalFileSystem localFileSystem = FileSystem.getLocal(new Configuration());
//4获取本地文件夹下所有文件信息
FileStatus[] fileStatus = localFileSystem.listStatus(new Path("D:\input"));
//5.遍历数据,获取每一个文件的信息
for (FileStatus fileSt : fileStatus) {
FSDataInputStream inputStream = localFileSystem.open(fileSt.getPath());
IOUtils.copy(inputStream, outputStream);
IOUtils.closeQuietly(inputStream);
}
IOUtils.closeQuietly(outputStream);
fileSystem.close();

}

--------------------------------------------------------------------------------------------------------------------------------------------------

 

原文地址:https://www.cnblogs.com/curedfisher/p/12575279.html