本文介紹了JAVA操作HDFS案例的簡(jiǎn)單實(shí)現(xiàn),分享給大家,也給自己做個(gè)筆記
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服務(wù)器:
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" )); } |
解析:
在開(kāi)發(fā)中我沒(méi)有引入“core-site.xml”配置文件,所以在本地調(diào)用時(shí)使用conf進(jìn)行配置“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上創(chuàng)建文件夾:
1
|
2
3
4
5
6
7
8
9
10
11
|
/** * 在hdfs更目錄下面創(chuàng)建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 不進(jìn)行遞歸查找 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()); } } |
運(yùn)行結(jié)果:
結(jié)果分析:
“listFiles“列出的是hdfs上所有文件的路徑,不包括文件夾。根據(jù)你的設(shè)置,支持遞歸查找。
”listStatus“列出的是所有的文件和文件夾,不支持遞歸查找。如許遞歸,需要自己實(shí)現(xiàn)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/mmd0308/article/details/74276564?utm_source=tuicool&utm_medium=referral