java Api操作hdfs文件系统
介绍java操作hadoop hdfs文件系统的常用api方法。
1、创建文件夹:public void mkdir() {
try {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://192.168.100.100:9000");
FileSystem fs = FileSystem.get(conf);
boolean result = fs.mkdirs(new Path("/myHadoop"));
System.out.println("创建文件夹结果:{}"+result);
} catch (Exception e) {
System.out.println("创建文件夹出错:"+ e);
}
}
2、写入文件:/**
* 写入文件
*/
@Test
public void write() throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://192.168.100.100:9000");
FileSystem fs = FileSystem.get(conf);
byte[] buff = "Hello hadoop".getBytes(); // 要写入的内容
String filename = "hdfs://192.168.100.100:9000/myHadoop/HdfsLearn"; //要写入的文件名
FSDataOutputStream os = fs.create(new Path(filename));
os.write(buff,0,buff.length);
System.out.println("写入文件:"+new Path(filename).getName());
os.close();
fs.close();
}
3、判断文件是否存在:/**
* 判断文件是否存在
*/
@Test
public void isExistFile() throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://192.168.100.100:9000");
FileSystem fs = FileSystem.get(conf);
String filename = "hdfs://192.168.100.100:9000/myHadoop/HdfsLearn";//文件路径
if(fs.exists(new Path(filename))){
System.out.println("文件存在");
}else{
System.out.println("文件不存在");
}
fs.close();
}
4、读取文件内容:/**
* 判断文件是否存在
*/
@Test
public void isExistFile() throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://192.168.100.100:9000");
FileSystem fs = FileSystem.get(conf);
String filename = "hdfs://192.168.100.100:9000/myHadoop/HdfsLearn";//文件路径
if(fs.exists(new Path(filename))){
System.out.println("文件存在");
}else{
System.out.println("文件不存在");
}
fs.close();
}
5、遍历文件夹:/**
* 遍历文件夹
*/
@Test
public void listFiles() throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://192.168.100.100:9000");
FileSystem fs = FileSystem.get(conf);
FileStatus[] statuses = fs.listStatus(new Path("hdfs://192.168.100.100:9000/"));
for (FileStatus file : statuses) {
if(file.isFile()){
//是文件
System.out.println("扫描到文件:"+file.getPath().getName());
}else{
//不是文件
System.out.println("扫描到文件夹:"+file.getPath().getName());
}
}
fs.close(); //关闭hdfs
}
6、删除文件:/**
* 删除文件
*/
@Test
public void delete() throws IOException {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://192.168.100.100:9000");
FileSystem fs = FileSystem.get(conf);
Path file = new Path("hdfs://192.168.100.100:9000/myHadoop/HdfsLearn");
boolean result = fs.delete(file, true);
System.out.println("删除文件结果:"+result);
fs.close(); //关闭hdfs
}
写一个主方法调用折6个实例看看执行的结果如何,代码如下:public void runHdfsLearn() throws IOException{
mkdir();//创建文件夹
isExistFile();//判断文件是否存在
write();//写入文件
isExistFile();//在判断文件是否存在
read();//读取文件内容
delete();//删除文件
isExistFile();//在判断文件是否存在
listFiles();//遍历主目录
}