JAVA操作HDFS案例的簡單實現(xiàn)
本文介紹了JAVA操作HDFS案例的簡單實現(xiàn),分享給大家,也給自己做個筆記
Jar包引入,pom.xml:
<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服務器:
/**
* 上傳文件到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"));
}
解析:
在開發(fā)中我沒有引入“core-site.xml”配置文件,所以在本地調(diào)用時使用conf進行配置“conf.set("fs.defaultFS","hdfs://hzq:9000");“,下面雷同。
將hdfs上文件下載到本地:
/**
* 將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上指定文件:
/**
* 刪除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)建文件夾:
/**
* 在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上所有的文件或文件夾:
@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());
}
}
運行結(jié)果:
結(jié)果分析:
“l(fā)istFiles“列出的是hdfs上所有文件的路徑,不包括文件夾。根據(jù)你的設置,支持遞歸查找。
”listStatus“列出的是所有的文件和文件夾,不支持遞歸查找。如許遞歸,需要自己實現(xiàn)。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Java數(shù)組擴容縮容與拷貝的實現(xiàn)和原理
這篇文章主要帶大家學習數(shù)組的擴容、縮容及拷貝,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05
SpringBoot注冊FilterRegistrationBean相關(guān)情況講解
這篇文章主要介紹了SpringBoot注冊FilterRegistrationBean相關(guān)情況,借助FilterRegistrationBean來注冊filter,可以避免在web.xml種配置filter這種原始的寫法2023-02-02
使用java技術(shù)抓取網(wǎng)站上彩票雙色球信息詳解
這篇文章主要介紹了使用java技術(shù)抓取網(wǎng)站上彩票雙色球信息詳解,web結(jié)果由html+js+css組成,html結(jié)構(gòu)都有一定的規(guī)范,數(shù)據(jù)動態(tài)交互可以通過js實現(xiàn)。,需要的朋友可以參考下2019-06-06

