Hadoop入門基礎配置(二)
Hadoop入門基礎配置<二>
本文為博主學習整理原創文章,如有不正之處請多多指教。
HDFS介面介紹
簡單的SHELL命令
檢視根目錄的目錄和檔案
hadoop fs -ls /
列出HDFS系統下所有的目錄和檔案
hadoop fs -R ls /
建立目錄(只能一級一級建立)
hadoop fs -mkdir < hdfs path>
複製
hadoop fs -cp < hdfs file > < hdfs file >
給檔案重新命名或者移動位置
hadoop fs -mv < hdfs file or dir >... < hdfs dir >
put命令
Hadoop fs -put /opt/jdk /
copyFromLocal 和moveFromLocal
hadoop fs -moveFromLocal < local src > ... < hdfs dst >
get命令
hadoop fs -get < hdfs file > < local file or dir>
刪除命令
Hadoop fs -rm -r
JAVA專案訪問Hadoop操作
新增依賴(三個)
hadoop-common
hadoop-client
hadoop-hdfs
編寫程式碼
模板:
//連結 FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"), new Configuration()); //拿資料 FSDataInputStream fis=fs.open(new Path("/text.txt")); //處理 FileOutputStream fos = new FileOutputStream("/root/"); //HDFS自帶一個工具類,將輸入輸出流進行連線 IOUtils.copyBytes(fis,fos,4096); //關閉 fs.close(); fis.close(); fos.close();
/* 建立一個檔案 */
// fs.createNewFile(new Path("/log/a.txt"));
報錯:
Exception in thread "main" org.apache.hadoop.security.AccessControlException: Permission denied: user=asus, access=WRITE, inode="/":root:supergroup:drwxr-xr-x
報錯原因:使用者許可權問題,要求root使用者進行操作,但是我們使用的是asus使用者。
解決方法1:在電腦本地建立一個root使用者,使用該使用者登入(不推薦)
解決方法2:傳入一個引數root
FileSystem fs = FileSystem.get(URI.create("hdfs://10.32.24.5:9000"), new Configuration(),"root");
解決方法3:執行的時候,以Jvm引數形式傳遞
解決方式4:系統引數
System.setProperty("HADOOP_USER_NAME","root");
建立目錄:fs.mkdirs(new Path("/test4"));
刪除檔案:fs.delete(new Path("/test4"),true);
True表示是否級聯刪除,如果是false,資料夾下面有檔案的話就不能刪除
建立檔案:fs.createNewFile(new Path("/test.txt"));
下載檔案(類似剪下):fs.copyToLocalFile(true,new Path("/test.txt"),new Path("d:/"));
上傳檔案到HDFS:
fs.copyFromLocalFile(new Path("d:/a.txt"), new Path("/test2.txt"));
報錯:
檔案追加:
InputStream is=new BufferedInputStream
(new FileInputStream("E:\\a.txt"));
FSDataOutputStream out=fs.append(new Path("/a.txt"));
IOUtils.copyBytes(is, out, 4096);
注意:fs一定要關閉,不然要報錯:
Failed to close file /test2.txt. Lease recovery is in progress
並且追加的時候副本要設定成1,不然追加成功不會顯示。