HDFS基本操作
你可以在命令行中输入hadoop fs -help
命令读取每个命令的详细帮助文件。
启动 Hadoop | start-dfs.sh |
新建目录 | hadoop fs -mkdir /dir |
上传文件 | hadoop fs -put helloworld.txt /usr/output |
列出文件 | hadoop fs -ls /usr |
移动文件 | hadoop fs -mv /usr/output/helloworld.txt / (移动到根目录) |
删除文件、空目录 | hadoop fs -rm /helloworld.txt |
删除非空文件夹 | 在-rm 之后加入一个-r 即可,用-rmr 也可 |
复制到本地 | hadoop fs -copyToLocal /usr/output/hello.txt /usr/local |
HDFS-JAVA接口
读取文件
// 获得文件uri
URI uri = URI.create("hdfs://localhost:9000/user/hadoop/task.txt");
// 读取默认配置文件,生成配置对象
Configuration config = new Configuration();
// 文件系统对象
FileSystem fs = FileSystem.get(uri, config);
InputStream in = null;
try {
// 获得输入流
in = fs.open(new Path(uri));
// 输出数据
IOUtils.copyBytes(in, System.out, 2048, false);
} catch (Exception e) {
IOUtils.closeStream(in);
}
FileSystem
是一个通用的文件系统API
,FileSystem
实例有几个静态工厂方法用来构造对象
上述使用的方法
public static FileSystem get(URI uri,Configuration conf)throws IOException
Configuration
对象封装了客户端或服务器的配置,通过设置配置文件读取类路径来实现(如:/etc/hadoop/core-site.xml
)
FileSystem
对象中的open()
方法返回的就是FSDataInputStream
对象
上传文件
// 本地文件
File localPath = new File("/develop/input/hello.txt");
// 上传地址
String hdfsPath = "hdfs://localhost:9000/user/tmp/hello.txt";
// 输入流对象
InputStream in = new BufferedInputStream(new FileInputStream(localPath));
// 配置对象
Configuration config = new Configuration();
// 文件系统对象
FileSystem fs = FileSystem.get(URI.create(hdfsPath),config);
long fileSize = localPath.length() > 65536 ? localPath.length() / 65536 : 1;
// dfs输出流
FSDataOutputStream out = fs.create(new Path(hdfsPath),new Progressable(){
// 显示进度
long fileCount = 0;
public void progress(){
System.out.println("总进度"+(fileCount/fileSize) * 100 + "%");
fileCount++;
}
});
// 上传文文件
IOUtils.copyBytes(in, out, 2048, true);
文件系统输出流
FSDataOutputStream out = fs.create(new Path(hdfsPath),new Progressable()...
删除文件
列出目录内容
String uri = "hdfs://localhost:9000/";
String path1 = "hdfs://localhost:9000/user/hadoop";
String path2 = "hdfs://localhost:9000/tmp/test";
Configuration config = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri),config);
// 删除文件或目录
fs.delete(new Path(path1),true);
fs.delete(new Path(path2),true);
// 列出文件夹和目录
Path[] paths = {new Path(uri),new Path("hdfs://localhost:9000/tmp")};
FileStatus[] status = fs.listStatus(paths);
Path[] listPaths = FileUtil.stat2Paths(status);
for(Path path : listPaths){
System.out.println(path);
}
参考链接 头歌实践教学平台