public static void listFile(String path) throws IOException{
//读取配置文件
Configuration conf = new Configuration();
//获取文件系统
FileSystem fs = FileSystem.get(URI.create("hdfs://hadoop1:9000"),conf);
//获取文件或目录状态
FileStatus[] fileStatus = fs.listStatus(new Path(path));
//打印文件的路径
for (FileStatus file : fileStatus) {
System.out.println(file.getPath());
}
//关闭文件系统
fs.close();
}
一、包依赖
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.6</version>
</dependency>
二、API的操作
1.创建目录
public static void mkdir(String path) throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://127.0.0.1:9000");
FileSystem fs = FileSystem.get(conf);
Path srcPath = new Path(path);
boolean isok = fs.mkdirs(srcPath);
if (isok) {
System.out.println("create dir ok!");
} else {
System.out.println("create dir failure");
}
fs.close();
}
2.删除目录
/**
* 删除目录
* @param path
*/
public static void rmdir(String path)throws Exception {
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(URI.create("hdfs://127.0.0.1:9000"), configuration);
boolean flag = fs.deleteOnExit(new Path("/test"));
if(flag) {
System.out.println("delete ok!");
}else {
System.out.println("delete failure");
}
//关闭文件系统
fs.close();
}
3.创建文件
public static void createFile(String dst , byte[] contents) throws IOException{
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
Path dstPath = new Path(dst);
FSDataOutputStream outputStream = fs.create(dstPath);
outputStream.write(contents);
outputStream.close();
fs.close();
System.out.println("文件创建成功!");
}
4.读取文件内容
public static void readFile(String uri) throws IOException {
//读取配置文件
Configuration conf = new Configuration();
//获取文件系统
FileSystem fs = FileSystem.get(URI.create("hdfs://localhost:9000"),conf);
InputStream in = null;
try {
in = fs.open(new Path(uri));
//复制到标准输出流
IOUtils.copyBytes(in, System.out, 4096,false);
} catch (Exception e) {
e.printStackTrace();
}finally{
IOUtils.closeStream(in);
}
}
5.查看文件目录
public static void listFile(String path) throws IOException{
//读取配置文件
Configuration conf = new Configuration();
//获取文件系统
FileSystem fs = FileSystem.get(URI.create("hdfs://hadoop1:9000"),conf);
//获取文件或目录状态
FileStatus[] fileStatus = fs.listStatus(new Path(path));
//打印文件的路径
for (FileStatus file : fileStatus) {
System.out.println(file.getPath());
}
//关闭文件系统
fs.close();
}
其它操作查看应的FileSystem的api
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有