HDFS的java访问接口——FileSystem
- 写文件 create
- 读取文件 open
- 删除文件 delete
- 创建目录 mkdirs
- 删除文件或目录 delete
- 列出目录的内容 listStatus
- 显示文件系统的目录和文件的元数据信息 getFileStatus
//打开 FileSystem
FileSystem getFileSystem(){
URI uri=new URI(“hdfs://192.168.111.129:9000/”);
FileSystem fileSystem = FileSystem.get(uri,new Configuration());
Return fileSystem ;
}
//读取文件
private static void readFile() throws Exception {
FileSystem fileSystem = getFileSystem();
FSDataInputStream openStream = fileSystem.open(new Path("hdfs://hadoop0:9000/aaa"));
IOUtils.copyBytes(openStream, System.out, 1024, false);
IOUtils.closeStream(openStream);
}
//创建目录
private static void mkdir() throws Exception {
FileSystem fileSystem = getFileSystem();
fileSystem.mkdirs(new Path("hdfs://hadoop0:9000/bbb"));
}
//删除目录
private static void rmdir() throws Exception {
FileSystem fileSystem = getFileSystem();
fileSystem.delete(new Path("hdfs://hadoop0:9000/bbb"));
}
//遍历目录
private static void list() throws Exception{
FileSystem fileSystem = getFileSystem();
FileStatus[] listStatus = fileSystem.listStatus(new Path("hdfs://hadoop0:9000/"));
for (FileStatus fileStatus : listStatus) {
String isDir = fileStatus.isDir()?"目录":"文件";
String name = fileStatus.getPath().toString();
System.out.println(isDir+" "+name);
}
}