HDFS API
package com.xiaoqiu;
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://hadoop104:8020");
Configuration configuration = new Configuration();
configuration.set("dfs.replication", "3");
String user = "hadoop";
fs = FileSystem.get(uri, configuration, user);
}
@After
public void close() throws IOException {
fs.close();
}
@Test
public void testMkdir() throws IOException {
fs.mkdirs(new Path("/testMkdir"));
}
@Test
public void upload() throws IOException {
fs.copyFromLocalFile(false, false, new Path("F:\\share\\phone_data.txt"), new Path("/testMkdir/phone_data.txt"));
}
@Test
public void download() throws IOException {
fs.copyToLocalFile(false,new Path("/testMkdir/phone_data.txt"),new Path("F:\\share\\phone_data1.txt"),true);
}
@Test
public void rm() throws IOException {
fs.delete(new Path("/sanguo/shuguo.txt"),true);
}
@Test
public void mv() throws IOException {
fs.rename(new Path("/sanguo/weiguo.txt"),new Path("/sanguo/wei.txt"));
}
@Test
public void fileDetail() throws IOException {
RemoteIterator<LocatedFileStatus> listFiles = fs.listFiles(new Path("/"), true);
while (listFiles.hasNext()){
LocatedFileStatus status = listFiles.next();
System.out.println(
status.getPermission()+"\t"
+status.getOwner()+"\t"
+status.getGroup()+"\t"
+status.getLen()+"\t"
+status.getModificationTime()+"\t"
+status.getReplication()+"\t"
+status.getBlockSize()+"\t"
+Arrays.toString(status.getBlockLocations()) +"\t"
+status.getPath().getName()
);
}
}
@Test
public void file() throws IOException {
FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
for (FileStatus fileStatus : fileStatuses) {
if (fileStatus.isFile()){
System.out.println("文件"+fileStatus.getPath().getName());
}else {
System.out.println("目录"+fileStatus.getPath().getName());
}
}
}
}