【筆記】JAVA API 訪問 HDFS
阿新 • • 發佈:2019-02-17
1.獲取HDFS檔案系統
public static FileSystem getFileSystem(){
//讀取配置檔案
Configuration conf = new Configuration();
//獲取檔案系統物件(在hadoop叢集上執行)
//FileSystem fs = FileSystem.get(conf);
//在本地執行
URI uri = new URI("hdfs://hostname:9000");
FileSystem fs = FileSystem.get(uri,conf);
}
2.建立檔案目錄
public static void mkdir(){
//獲取檔案系統
FileSystem fs = getFileSystem();
//建立檔案目錄
fs.mkdir(new path(" "));
//釋放資源
fs.close();
3.檔案上傳至HDFS
public static void copyToHDFS(){
FileSystem fs = getFileSystem();
//從···上傳
Path srcpath = new Path(" ");
//上傳到···
Path dstpath = new Path(" ");
//上傳檔案
fs.copyFromLocalFile(srcpath,dstpath);
//釋放資源
fs.close();
4.從HDFS下載檔案
public static void getFille(){
FileSystem fs = getFileSystem();
//從···上傳
Path srcpath = new Path(" ");
//上傳到···
Path dstpath = new Path(" ");
//上傳檔案
fs.copyToLacalFile(srcpath,dstpath);
//釋放資源
fs.close();
5.獲取目錄下的所有檔案
public static void ListAllFill(){
FileSystem fs = getFileSystem();
//列出目錄內容
FileStatus[] status = fs.ListStatus(new Path(" "));
//獲取目錄下的所有檔案路徑
Path[] listedPaths = FileUtil.stat2Paths(status);
//迴圈輸出目錄檔案
for(Path p : listedPaths){
System.out.println(p);
}
fs.close();
}
6.檢視某個檔案在HDFS叢集的位置
public static void getFileLocal(){
FileSystem fs = getFileSystem();
//檔案路徑
Path path = new Path();
//獲取檔案目錄
FileStatus fileStatus=fs.getFileStatus(path);
//獲取檔案塊位置資訊
BlockLocation[] blkLocation = fs.getFileBlockLocation(fileStatus,0,fileStatus.getln());
//迴圈輸出塊資訊
for(int i=0;i<blkLocation.length;i++){
//獲取所有節點資訊
String[] hosts = blkLocation(i).getHosts();
System.out.println("block"+i+"_location"+hosts[0];
}
}
7.刪除檔案或者檔案目錄
public static void rmdir(){
FileSystem fs = getFileSystem();
fs.delete(new Path(" "),true);
fs.close();
8.獲取HDFS叢集節點資訊
public static void getHDFSNodes(){
FileSystem fs = getFileSystem();
//獲取分散式檔案系統
DistributedFileSystem hdfs = (DistributedFileSystem)fs;
//獲取所有節點
DataNodeInfo[] dataNodeStatus = hdfs.getDataNodeStats();
//迴圈列印所有節點
for(int i=0; i<dataNodeStatus.length;i++){
System.out.println("DataNode_"+i+"_Name:"+dataNodeStatus[i].getHostName();
}
}