package com.howey.hdfs;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
public class HdfsClient {
private FileSystem fs;
@Before
public void init() throws URISyntaxException, IOException, InterruptedException {
URI uri = new URI("hdfs://hadoop102:8020");
Configuration entries = new Configuration();
entries.set("dfs.replication", "2");
String user = "howey";
fs = FileSystem.get(uri, entries, user);
}
@After
public void close() throws IOException {
fs.close();
}
@Test
public void testMkdir() throws IOException {
fs.mkdirs(new Path("/howey1"));
}
@Test
public void testUpload() throws IOException {
fs.copyFromLocalFile(false, true,
new Path("C:\\Users\\Administrator\\Desktop\\test\\js\\bootstrap-datetimepicker.min.js"),
new Path("/howey/js/bootstrap-datetimepicker.min.js"));
}
@Test
public void testGet() throws IOException {
fs.copyToLocalFile(false, new Path("/howey/js"), new Path("C:\\Users\\Administrator\\Desktop\\test\\js\\"), true);
}
@Test
public void testDel() throws IOException {
fs.delete(new Path("/howey/js"), false);
}
@Test
public void testRenameAndMv() throws IOException {
Path bootPath = new Path("/howey/bootstrap");
if (!fs.exists(bootPath)) {
fs.mkdirs(bootPath);
}
fs.rename(new Path("/howey/js/bootstrap-datetimepicker.js"), new Path("/howey/bootstrap/bootstrap-datetimepicker.js"));
}
@Test
public void fileDetail() throws IOException {
RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/howey"), true);
while (listFiles.hasNext()) {
LocatedFileStatus info = listFiles.next();
Path path = info.getPath();
System.out.println("========" + path);
System.out.println("========" + info.getGroup());
System.out.println("========" + info.getOwner());
System.out.println("========" + info.getBlockSize());
System.out.println("========" + info.getLen());
System.out.println("========" + info.getPermission());
System.out.println("========" + info.getReplication());
BlockLocation[] blockLocations = info.getBlockLocations();
System.out.println("========" + Arrays.toString(blockLocations));
}
}
@Test
public void judgeFileStatus() throws IOException {
FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
for (FileStatus status : fileStatuses) {
String name = status.getPath().getName();
if (status.isFile()) {
System.out.println("==========" + name + " is a file");
} else {
System.out.println("==========" + name + " is not a file");
}
}
}
}