HDFS的API操作-获取FileSystem方式
生活随笔
收集整理的這篇文章主要介紹了
HDFS的API操作-获取FileSystem方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
HDFS 的 API 操作
導入 Maven 依賴
<repositories><repository><id>cloudera</id><url>https://repository.cloudera.com/artifactory/cloudera-repos/</url></repository> </repositories> <dependencies><dependency><groupId>jdk.tools</groupId><artifactId>jdk.tools</artifactId><version>1.8</version><scope>system</scope><systemPath>${JAVA_HOME}/lib/tools.jar</systemPath></dependency><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-common</artifactId><version>3.0.0</version><scope>provided</scope></dependency><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-hdfs</artifactId><version>3.0.0</version></dependency><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-hdfs-client</artifactId><version>3.0.0</version><scope>provided</scope></dependency><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-client</artifactId><version>3.0.0</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency> </dependencies>概述
在 Java 中操作 HDFS, 主要涉及以下 Class:
-
Configuration
- 該類的對象封轉了客戶端或者服務器的配置
-
FileSystem
-
該類的對象是一個文件系統對象, 可以用該對象的一些方法來對文件進行操作, 通過 FileSystem 的靜態方法 get 獲得該對象
? ? FileSystem fs = FileSystem.get(conf)- get 方法從 conf 中的一個參數 fs.defaultFS 的配置值判斷具體是什么類型的文件系統
- 如果我們的代碼中沒有指定 fs.defaultFS, 并且工程 ClassPath 下也沒有給定相應的配置, conf 中的默認值就來自于 Hadoop 的 Jar 包中的 core-default.xml
- 默認值為 file:///, 則獲取的不是一個 DistributedFileSystem 的實例, 而是一個本地文件系統的客戶端對象
-
獲取 FileSystem 的幾種方式
第一種方式
@Test public void getFileSystem() throws URISyntaxException, IOException {Configuration configuration = new Configuration();FileSystem fileSystem = FileSystem.get(new URI("hdfs://192.168.52.250:8020"), configuration);System.out.println(fileSystem.toString()); }第二種方式
@Test public void getFileSystem2() throws URISyntaxException, IOException {Configuration configuration = new Configuration();configuration.set("fs.defaultFS","hdfs://192.168.52.250:8020");FileSystem fileSystem = FileSystem.get(new URI("/"), configuration);System.out.println(fileSystem.toString()); }第三種方式
@Test public void getFileSystem3() throws URISyntaxException, IOException {Configuration configuration = new Configuration();FileSystem fileSystem = FileSystem.newInstance(new URI("hdfs://192.168.52.250:8020"), configuration);System.out.println(fileSystem.toString()); }第四種方式
@Test public void getFileSystem4() throws Exception{Configuration configuration = new Configuration();configuration.set("fs.defaultFS","hdfs://192.168.52.250:8020");FileSystem fileSystem = FileSystem.newInstance(configuration);System.out.println(fileSystem.toString()); }?
?
?
?
總結
以上是生活随笔為你收集整理的HDFS的API操作-获取FileSystem方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDFS数据的写入过程
- 下一篇: HDFS的API操作-获取文件列表信息