1、在HDFS文件系统中新增目录
新增代码
查看结果
2、删除目录
删除代码
查看结果
3、查看目录
代码
执行结果
代码
package com.lizh.hadoop.hdfs;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public class HdfsApp {
public static FileSystem getFileSystem() throws IOException{
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
return fs;
}
/**
* 利用HDSF的api读取文件内容
* @param path1
*/
public static void readFile(String path1) {
try {
FileSystem fs = getFileSystem();
Path path = new Path(path1);
FSDataInputStream in = fs.open(path);
IOUtils.copyBytes(in, System.out, 4000, false);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 利用HDFS的api上传文件
*/
public static void putFile(){
//把/opt/modules/hadoop-2.5.0/wc.input 内容写入到 /user/beifeng/put-wc.input
//write file
FileInputStream fisin =null;
FSDataOutputStream fsoutstream =null;
try {
String filename="/user/beifeng/put-wc.input";//文件系统目录
Path inputpath = new Path(filename);
FileSystem fs = getFileSystem();//获取文件系统
fsoutstream = fs.create(inputpath);
fisin = new FileInputStream(new File("/opt/modules/hadoop-2.5.0/wc.input"));//本地系统目录文件
IOUtils.copyBytes(fisin, fsoutstream, 4000, false);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
IOUtils.closeStream(fsoutstream);
IOUtils.closeStream(fisin);
}
}
/**
* 利用HDFS的api创建目录
*/
public static void createDir(String filepath){
try {
FileSystem fs = getFileSystem();//获取文件系统
fs.mkdirs(new Path(filepath));
fs.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 删除目录
* @param filepath
*/
public static void deleteDir(String filepath){
try {
FileSystem fs = getFileSystem();//获取文件系统
fs.deleteOnExit(new Path(filepath));
fs.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void listDir(){
try {
FileSystem fs = getFileSystem();//获取文件系统
FileStatus[] fslarray = fs.listStatus(new Path("/user/beifeng"));
for(FileStatus files:fslarray){
System.out.println(files.getPath());
}
fs.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
}
}
public static void main(String[] args) throws Exception{
listDir();
}
}
网友评论