IO流操作HDFS
寫在前面:
我的博客已遷移至自建服務器:博客傳送門,CSDN博客暫時停止,如有機器學習方面的興趣,歡迎來看一看。
此外目前我在gitHub上準備一些李航的《統計學習方法》的實現算法,目標將書內算法全部手打實現,歡迎參觀并打星。GitHib傳送門
上傳文件Demo
@Test public void putFileToHDFS() throws IOException, InterruptedException, URISyntaxException {//1.獲取文件系統Configuration configuration = new Configuration();FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");//2.獲取輸入流FileInputStream fis = new FileInputStream(new File("e:/hello.txt"));//3.獲取輸出流FSDataOutputStream fos = fs.create(new Path("/hello3.txt"));//4.流對拷IOUtils.copyBytes(fis, fos, configuration);//5.關閉資源IOUtils.closeStream(fis);IOUtils.closeStream(fos);if(fs != null) {try {fs.close();}catch (IOException ex) {System.out.println("文件關閉失敗");}} }下載文件Demo
@Test public void getFileFromHDFS() throws IOException, InterruptedException, URISyntaxException {//1.獲取文件系統Configuration configuration = new Configuration();FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "atguigu");//2.獲取輸入流FSDataInputStream fis = fs.open(new Path("/hello3.txt"));//3.獲取輸出流FileOutputStream fos = new FileOutputStream(new File("e:/hello1.txt"));//4.流對拷IOUtils.copyBytes(fis, fos, configuration);//5.關閉資源IOUtils.closeStream(fis);IOUtils.closeStream(fos);if(fs != null) {try {fs.close();}catch(IOException ex){System.out.println(ex.getMessage());}} }定位文件讀取
本Demo中,在/user/atguigu中有文件hadoop-2.7.2.tar.gz,其大小為188.5M,由于HDFS文件塊大小為128M,所以該文件在HDFS系統中分兩塊存。
正常下載時,HDFS會將整個文件下載至本地。本Demo通過將文件分開定位的方式,按照塊的大小來分兩次讀取文件。
總結
- 上一篇: JAVA操作Hadoop
- 下一篇:無