配置windows平台的Hadoop環境
在 windows 上做 HDFS 用戶端應用開發,需要設定 Hadoop 環境,而且要求是windows 平台編譯的 Hadoop,不然會報以下的錯誤:
Failed to locate the winutils binary in the hadoop binary path java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.
參考:https://blog.csdn.net/huyishero/article/details/72896484
建立Maven工程,引入pom依賴
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.4</version>
</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 的執行個體,而是一個本地檔案系統的用戶端對象。
示例代碼
1 public class TestHDFS {
2
3 public static void main(String[] args) throws Exception{
4 Configuration conf = new Configuration();
5 //指定使用的是hdfs檔案系統
6 // conf.set("fs.defaultFS","hdfs://node-1:9000");
7
8 //FileSystem是hadoop操作檔案系統的核心類
9 //通過FileSystem的靜态方法擷取檔案系統用戶端對象
10 // FileSystem fs = FileSystem.get(conf);
11 //設定uri,conf,使用者身份
12 FileSystem fs = FileSystem.get(new URI("hdfs://node-1:9000"),conf,"root");
13
14 //建立一個檔案夾
15 // fs.mkdirs(new Path("/createByJava"));
16 //上傳檔案
17 // fs.copyFromLocalFile(new Path("D:\\test.txt"),new Path("/createByJava/test.txt"));
18 //下載下傳檔案
19 // fs.copyToLocalFile(new Path("/createByJava/test.txt"),new Path("D:\\test\\test.txt"));
20
21 //stream形式讀取本地的一個檔案
22 FileInputStream in = new FileInputStream(new File("D:\\test.txt"));
23 //建立一個檔案
24 FSDataOutputStream out = fs.create(new Path("/test.txt"));
25 //stream形式将本地檔案上傳到hdfs
26 IOUtils.copy(in,out);
27
28 fs.close();
29 }
30 }