我們向/maven下上傳一個文件。 要用到的api是put (或者copyFormLocalFile)。核心代碼如下。
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {// 1 獲取文件系統Configuration configuration = new Configuration();FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "root");// 2 上傳文件fs.copyFromLocalFile(new Path("d:/sunwukong.txt"), new Path("/maven"));// 3 關閉資源fs.close();
}
上傳結束之后,回到hdfs的UI界面去檢查是否成功。
動態設置副本份數(參數優先級)
默認情況下,上傳的文件會被保存3份,如果需要的話,我們可以隨時去修改這個設置參數。
參數優先級排序:(1)客戶端代碼中設置的值?>(2)然后是服務器的自定義配置(xxx-site.xml)?>(3)服務器的默認配置(xxx-default.xml)
參考代碼如下:
@Test
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {// 1 獲取文件系統Configuration configuration = new Configuration();configuration.set("dfs.replication", "2");FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "root");// 2 上傳文件fs.copyFromLocalFile(new Path("d:/sunwukong.txt"), new Path("/xiyou/huaguoshan"));// 3 關閉資源fs.close();
}
修改這個值之后,我們再去重新上傳一個新的文件,并檢查是否在hdfs的UI面板中能看到這個數值的變化。
HDFS文件下載
接下來,我們看如何去下載文件。這個過程需要調用copyToLocalFile這個API。具體的測試代碼如下:
@Test
public void testCopyToLocalFile() throws IOException, InterruptedException, URISyntaxException{// 1 獲取文件系統Configuration configuration = new Configuration();FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "root");// 2 執行下載操作// boolean delSrc 指是否將原文件刪除// Path src 指要下載的文件路徑// Path dst 指將文件下載到的路徑// boolean useRawLocalFileSystem 是否開啟文件校驗fs.copyToLocalFile(false, new Path("/xiyou/huaguoshan/sunwukong.txt"), new Path("d:/sunwukong2.txt"), true);// 3 關閉資源fs.close();
}
注意:如果執行上面代碼,下載不了文件,有可能是你電腦的微軟支持的運行庫少,需要安裝一下微軟運行庫。