Hadoop 學習筆記(七)HDFS 客戶端操作(下)
阿新 • • 發佈:2020-10-12
上面我們學的API操作HDFS系統都是框架封裝好的。那麼如果我們想自己實現上述API的操作該怎麼實現呢?我們可以採用IO流的方式實現資料的上傳和下載。
1、上傳本地檔案到 HDFS ;
public static Configuration conf = new Configuration(); // 1、 本地檔案上傳 HDFS 系統 @Test public void putIOTest() throws IOException, InterruptedException, URISyntaxException { // 1、獲取 HDFS 客戶端物件 FileSystem fs = FileSystem.get(newURI("hdfs://hadoop103:9000"), conf, "hui"); // 2、獲取 I/O 流 FileInputStream fis = new FileInputStream(new File("E:/workspaced/data/zhouzhiruo.txt")); // 3、獲取輸出流 FSDataOutputStream fos = fs.create(new Path("/yttlj/gmd/wyx.txt")); // 4、流的對拷 IOUtils.copyBytes(fis, fos, conf);// 5、關閉資源 IOUtils.closeStream(fos); IOUtils.closeStream(fis); fs.close(); System.out.println(" ok "); }
2、從 HDFS 檔案系統獲取資料到本地
@Test public void getIOTest() throws IOException, InterruptedException, URISyntaxException { // 1、獲取 HDFS 客戶端物件 FileSystem fs = FileSystem.get(newURI("hdfs://hadoop103:9000"), conf, "hui"); // 2、獲取 I/O 流 FSDataInputStream fis = fs.open(new Path("/yttlj/gmd/wyx.txt")); // 3、獲取輸出流 FileOutputStream fos = new FileOutputStream(new File("E:/workspaced/data/wyx_fw.txt")); // 4、流的對拷 IOUtils.copyBytes(fis, fos, conf); // 5、關閉資源 IOUtils.closeStream(fos); IOUtils.closeStream(fis); fs.close(); System.out.println(" ok "); }
3、從 HDFS 檔案系統定位讀取資料(只讀取 128 M)
@Test public void getIO1blockTest() throws IOException, InterruptedException, URISyntaxException { // 1、獲取 HDFS 客戶端物件 FileSystem fs = FileSystem.get(new URI("hdfs://hadoop103:9000"), conf, "hui"); // 2、獲取 I/O 流 FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz")); // 3、獲取輸出流 FileOutputStream fos = new FileOutputStream(new File("E:/workspaced/data/hadoop-2.7.2.tar.gz.part1")); // 4、使用最傳統方式讀取 128 M 資料 byte[] buf = new byte[1014]; for (int i = 0; i < 1024 * 128; i++) { fis.read(buf); fos.write(buf); } // 5、關閉資源 IOUtils.closeStream(fos); IOUtils.closeStream(fis); fs.close(); System.out.println(" ok "); }
4、從 HDFS 檔案系統定位讀取資料(從128 M 開始讀取)
@Test public void getIO2blockTest() throws IOException, InterruptedException, URISyntaxException { // 1、獲取 HDFS 客戶端物件 FileSystem fs = FileSystem.get(new URI("hdfs://hadoop103:9000"), conf, "hui"); // 2、獲取 I/O 流 FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz")); // ***** 設定指定讀取起點 ****** fis.seek(1024 * 1024 * 128); // 3、獲取輸出流 FileOutputStream fos = new FileOutputStream(new File("E:/workspaced/data/hadoop-2.7.2.tar.gz.part2")); // 4、流資料 copy IOUtils.copyBytes(fis, fos, conf); // 5、關閉資源 IOUtils.closeStream(fos); IOUtils.closeStream(fis); fs.close(); System.out.println(" ok "); }