package com.jinghang.hdfsclient;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.mapred.IFileInputStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
public class HdfsClient {
private Configuration configuration;
private FileSystem fileSystem;
@Before
public void init() throws IOException, InterruptedException {
System.out.println("即将开始执行");
this.configuration=new Configuration();
this.fileSystem =FileSystem.get(
//URI:统一资源标识符(包含URN、URL)
//URL:统一资源定位符
//URN:统一资源名称
URI.create("hdfs://xiaokai01:9000"),
configuration,
"xiaokai"
);
}
@Test
public void put () throws IOException {
//获取一个hdfs的文件抽象对象(ctrl+alt+v)
// Configuration configuration = new Configuration();
// FileSystem fileSystem = FileSystem.get(
// //URI:统一资源标识符(包含URN、URL)
// //URL:统一资源定位符
// //URN:统一资源名称
// URI.create("hdfs://hadoop01:9000"),
// configuration,
// "jinghang"
// );//alt+enter
//将本地文件上传至hdfs
//本地文件路径
Path localPath = new Path("C:\develop");
//hdfs文件路经
Path hdfslPath = new Path("/log100/log.txt");
//将本地文件上传至hdfs通过copyFromLocalFile方法
fileSystem.copyFromLocalFile(localPath,hdfslPath);
fileSystem.close();
}
@Test
public void mkdir() throws IOException {
Path class222 = new Path("/class222");
boolean b = fileSystem.mkdirs(class222);
if(b){
System.out.println("文件创建成功");
}
else{
System.out.println("文件创建失败");
}
}
@Test
public void rename() throws IOException {
//获取需要重命名的文件的路径
Path hdfsPath = new Path("/class222");
//重命名的名称
Path newPath = new Path("/class999");
boolean b = fileSystem.rename(hdfsPath, newPath);
if (b){
System.out.println("文件名修改成功");
}
else {
System.out.println("文件名修改失败");
}
}
//文件追加
@Test
public void append() throws IOException {
//要追加的文件路径(hdfs)
Path hdfsPath = new Path("/log200/log.txt");
// //本地文件的路径
String localPath = "C:\develop";
//hdfs的文件输出流
FSDataOutputStream append = fileSystem.append(hdfsPath, 1024);
//本地文件的输入流
FileInputStream inputStream = new FileInputStream(localPath);
IOUtils.copyBytes(inputStream,append,1024,true);
//手动关闭输入流和输出流
inputStream.close();
append.close();
}
//删除文件
@Test
public void delete() throws IOException {
//指定需要删除的文件的路径
Path hdfsPath = new Path("/log100");
boolean b = fileSystem.delete(hdfsPath, true);
if(b){
System.out.println("文件删除成功");
}else {
System.out.println("文件删除失败");
}
}
//读取文件和文件夹
@Test
public void readFileAndDir() throws IOException {