前面4.1到4.3节的准备工作,本节正式进入HDFS的Java API 部分,将通过一个简单例子演示如何在Windows下通过Eclipse开发Hadoop(HDFS)应用程序,注意此部分不需要hadoop-eclipse-plugin插件。
通过HDFS 命令方式将本地words.txt文件上传到HDFS上
[root@node1 ~]# hdfs dfs -put /root/words.txt input
[root@node1 ~]# hdfs dfs -ls /user/root/input
Found 1 items
-rw-r--r-- 3 root supergroup 55 2017-05-17 10:32 /user/root/input/words.txt
[root@node1 ~]# hdfs dfs -cat /user/root/input/words.txt
Java Java
Hadoop Hadoop Hadoop
Hello World Hello World
[root@node1 ~]#
在Maven项目hdfsDemo的新建Java类ReadFile
在ReadFile.java类中编辑代码如下:
package cn.hadron.hdfsDemo;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public class ReadFile {
public static void main(String[] args) throws IOException {
String uri="hdfs://192.168.80.131:9000/user/root/input/words.txt";
Configuration cfg=new Configuration();
FileSystem fs= FileSystem.get(URI.create(uri),cfg);
InputStream in=null;
try{
in=fs.open(new Path(uri));
IOUtils.copyBytes(in, System.out,4096,false);
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
IOUtils.closeStream(in);
}
}
}
程序说明:
FileSystem fs = FileSystem.get(conf);
通过FileSystem的静态方法get获得该对象。String uri="hdfs://192.168.80.131:9000/user/root/input/word.txt"
要与core-site.xml文件中的fs.defaultFS配置对应,其值是hdfs://node1:9000
。由于本地Windows系统的hosts文件没有配置node1,所以这里需要IP地址表示。右键单击ReadFile类,在弹出的快捷菜单中选择“Run As”–> “Java Application”。 等待数秒后,在Eclipse底部的Console窗口中将看到输入结果。
将该类导出为 ReadFile.jar:
在导出目录可以找到jar包,此处在桌面上可以看到
将jar上传集群中一个节点下 ,比如node3。 这里还是通过Xftp上传
在node3(192.168.80.133)节点上执行命令:
[root@node3 ~]# hadoop jar ReadFile.jar cn.hadron.hdfsDemo.ReadFile