本文介紹了JAVA操作HDFS案例的簡單實現,分享給大家,也給自己做個筆記
Jar包引入,pom.xml:
1
|
2
3
4
5
6
7
8
9
10
|
< dependency > < groupId >org.apache.hadoop</ groupId > < artifactId >hadoop-common</ artifactId > < version >2.8.0</ version > </ dependency > < dependency > < groupId >org.apache.hadoop</ groupId > < artifactId >hadoop-hdfs</ artifactId > < version >2.8.0</ version > </ dependency > |
將本地文件上傳到hdfs服務器:
1
|
2
3
4
5
6
7
8
9
10
|
/** * 上傳文件到hdfs上 */ @Test public void upload() throws IOException { Configuration conf = new Configuration(); conf.set( "fs.defaultFS" , " hdfs://hzq:9000 " ); FileSystem fs = FileSystem.get(conf); fs.copyFromLocalFile( new Path( "/home/hzq/jdk1.8.tar.gz" ), new Path( "/demo" )); } |
解析:
在開發中我沒有引入“core-site.xml”配置文件,所以在本地調用時使用conf進行配置“conf.set("fs.defaultFS","hdfs://hzq:9000");“,下面雷同。
將hdfs上文件下載到本地:
1
|
2
3
4
5
6
7
8
9
10
|
/** * 將hdfs上文件下載到本地 */ @Test public void download() throws IOException { Configuration conf = new Configuration(); conf.set( "fs.defaultFS" , " hdfs://hzq:9000 " ); FileSystem fs = FileSystem.newInstance(conf); fs.copyToLocalFile( new Path( "/java/jdk1.8.tar.gz" ), new Path( "/home/hzq/" )); } |
刪除hdfs上指定文件:
1
|
2
3
4
5
6
7
8
9
10
11
|
/** * 刪除hdfs上的文件 * @throws IOException */ @Test public void removeFile() throws IOException { Configuration conf = new Configuration(); conf.set( "fs.defaultFS" , " hdfs://hzq:9000 " ); FileSystem fs = FileSystem.newInstance(conf); fs.delete( new Path( "/demo/jdk1.8.tar.gz" ), true ); } |
在hdfs上創建文件夾:
1
|
2
3
4
5
6
7
8
9
10
11
|
/** * 在hdfs更目錄下面創建test1文件夾 * @throws IOException */ @Test public void mkdir() throws IOException { Configuration conf = new Configuration(); conf.set( "fs.defaultFS" , " hdfs://hzq:9000 " ); FileSystem fs = FileSystem.newInstance(conf); fs.mkdirs( new Path( "/test1" )); } |
列出hdfs上所有的文件或文件夾:
1
|
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@Test public void listFiles() throws IOException { Configuration conf = new Configuration(); conf.set( "fs.defaultFS" , " hdfs://hzq:9000 " ); FileSystem fs = FileSystem.newInstance(conf); // true 表示遞歸查找 false 不進行遞歸查找 RemoteIterator<LocatedFileStatus> iterator = fs.listFiles( new Path( "/" ), true ); while (iterator.hasNext()){ LocatedFileStatus next = iterator.next(); System.out.println(next.getPath()); } System.out.println( "----------------------------------------------------------" ); FileStatus[] fileStatuses = fs.listStatus( new Path( "/" )); for ( int i = 0 ; i < fileStatuses.length; i++) { FileStatus fileStatus = fileStatuses[i]; System.out.println(fileStatus.getPath()); } } |
運行結果:
結果分析:
“listFiles“列出的是hdfs上所有文件的路徑,不包括文件夾。根據你的設置,支持遞歸查找。
”listStatus“列出的是所有的文件和文件夾,不支持遞歸查找。如許遞歸,需要自己實現。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/mmd0308/article/details/74276564?utm_source=tuicool&utm_medium=referral