hadoop集羣搭建好之後,本地通過java api訪問hadoop集羣,java代碼如下
package ch4;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
public class FileSystemOperationDemo3 {
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
String dfspath = "hdfs://cmaster:8020/TestDir";
Path pathdir = new Path(dfspath);
Path file = new Path(pathdir + "test.txt");
FileSystem fs = pathdir.getFileSystem(conf);
fs.mkdirs(pathdir);
System.out.println("Write to" + conf.get("fs.default.name"));
// d盤下需要存在log.txt文件
fs.copyFromLocalFile(new Path("d://log.txt"), file);
fs.copyToLocalFile(file, new Path("e://"));
boolean bn = fs.rename(file, new Path(
"hdfs://cmaster:8020/TestDir/renamelog.txt"));
System.out.println(bn);
DistributedFileSystem hdfs = (DistributedFileSystem) fs;
DatanodeInfo[] dataNodeStatus = hdfs.getDataNodeStats();
for (DatanodeInfo datanodeInfo : dataNodeStatus) {
System.out.println("DataNode節點的名字" + datanodeInfo.getHostName());
}
boolean bndel = fs.delete(pathdir, true);
System.out.println("刪除HDFS目錄及文件:" + bndel);
fs.close();
}
}
上圖是運行錯誤的結果圖,從畫橫線的地方可以看出是權限錯誤,出現Access denied for user Administrator. Superuser privilege is required的錯誤信息:
首先在Linux下輸入:hadoop fs -chmod 777 / 命令,開啓權限(可讀可寫可執行)
可以有用這種解決方式:點擊跳轉到目標鏈接
也可以用另一種方式:由於是訪問權限問題,我們在訪問Hadoop的時候加入System.setProperty("HADOOP_USER_NAME", "root");
其中的“root”是具有訪問hadoop集羣權限的用戶名,即管理員權限。
修改完代碼讓我們來運行以下代碼,看看能否訪問hadoop服務
代碼運行成功