全部課程
發(fā)布時間: 2019-09-08 13:37:30
工程目錄
?
?導(dǎo)入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;
/**
* 構(gòu)建HdfsClient來操作hadoop集群
*/
public class HdfsClient {
private FileSystem fs = null;
/**
* 構(gòu)建分布式文件系統(tǒng)的操作對象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);
//循環(huán)
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();
}
}
}