Java与Hadoop的交互
一.创建maven工程完成交互
创建过程请参考这篇博客:
链接: link.
二.修改pom.xml
1.修改版本
2.导入依赖包
三.交互程序
在App的下一级目录创建一个java文件
1.java查看hadoop文件
public class testhdfs {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://192.168.198.111:9000");
FileSystem fs = FileSystem.get(conf);
//上面三步可以合并成这一步进行
// FileSystem fs=FileSystem.get(new URI("hdfs://192.168.198.111:9000"),new Configuration(),"root");
DataInputStream is = fs.open(new Path("/zhu/README.txt"));
int tmp;
while ((tmp = is.read()) != -1) {
System.out.print((char) tmp);
}
}
2.用变量实现对Hadoop文件的查看与本地向Hadoop传输文件
public static void main(String[] args) throws Exception {
FileSystem fs=FileSystem.get(new URI("hdfs://192.168.198.111:9000"),new Configuration(),"root");
//从hadoop复制到本地
// fs.copyToLocalFile(new Path(args[0]),new Path(args[1]));
//从本地复制到hadoop
fs.copyFromLocalFile(new Path(args[1]),new Path(args[0]));
}
args[0]----hadoop文件路径
args[1]----本地路径
3.实现创建目录和删除目录
//创建文件系统连接hadoop和java
FileSystem fs=FileSystem.get(new URI("hdfs://192.168.198.111:9000"),new Configuration(),"root");
//增加hdfs目录
// fs.mkdirs(new Path("/hello/nihao/womenshihaopengyou"));
//删除目录womenshihaopengyou
fs.deleteOnExit(new Path("/hello/nihao/womenshihaopengyou"));
//删除目录/hello及所有子目录
fs.deleteOnExit(new Path("/hello"));