发布时间: 2019-09-08 13:37:30
工程目录
导入Maven的依赖包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
package net.togogo.hdfs;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
/**
* 构建HdfsClient来操作hadoop集群
*/
public class HdfsClient {
private FileSystem fs = null;
/**
* 构建分布式文件系统的操作对象FileSystem
*/
@Before
public void init() {
System.out.println(" init methon start ....");
try {
Configuration conf = new Configuration();
//连接集群的地址
URI uri = new URI("hdfs://192.168.20.32:9000");
fs = FileSystem.get(uri, conf, "hd");
System.out.println("FileSystem---->" + fs);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(" init methon end ....");
}
/**
* 命令 hadoop fs -ls /
*/
@Test
public void listRoot() {
try {
System.out.println("listRoot method ....");
//访问 hadoop fs -ls /
RemoteIterator<LocatedFileStatus> it = fs.listFiles(new Path("/"), true);
//循环
while (it.hasNext()) {
LocatedFileStatus lf = it.next();
System.out.println(lf.getPath().getName());
}
fs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 命令 hadoop fs -mkdir /test0831
*/
@Test
public void mkdir() {
try {
Path path = new Path("/test0831");
fs.mkdirs(path);
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 命令 hadoop fs -put F:/hello.log /
*/
@Test
public void upload() {
try {
Path src = new Path("F:/hello.log");
Path dst = new Path("/");
fs.copyFromLocalFile(src, dst);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 命令 hadoop fs -get /hello.log F:/dsthello.log
*/
@Test
public void download() {
try {
Path src = new Path("/hello.log");
Path dst = new Path("F:/dsthello.log");
fs.copyToLocalFile(src, dst);
} catch (IOException e) {
e.printStackTrace();
}
}
}
上一篇: Java培训_SpringCloud Eureka服务注册中心
下一篇: 人工智能AI培训_垃圾邮件识别案例