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 {
//listStatus:讀取文件和文件夾
Path hdfsPath =