系统环境介绍
用虚拟机VirtualBox,用VMWare也是可以的。
如果要自己进行Hadoop搭建的话,耗时长,学校课程,现成的给你。
镜像是厦门大学数据库实验室放出的,文件大小6GB。
下载网址以及说明:大数据Linux实验环境虚拟机镜像文件
Linux dblab-VirtualBox 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
使用Hadoop
打开终端,启动hadoop:
cd /usr/local/hadoop
./bin/start-dfs.sh
(可以查看端口:netstat -tunpl | grep 9000)
看一些命令用法:
./bin/hdfs dfs
对比:
hadoop fs适用于任何不同的文件系统,比如本地文件系统和HDFS文件系统
hadoop dfs只能适用于HDFS文件系统
hdfs dfs跟hadoop dfs的命令作用一样,也只能适用于HDFS文件系统
在dfs里创建一个目录:
./bin/hdfs dfs -mkdir -p /user/hadoop
因为终端用户是hadoop,所以创建/user/hadoop作为hdfs的用户目录,相对路径就从这里开始。
查看目录:
./bin/hdfs dfs -ls /user
创建文件:
./bin/hdfs dfs -touchz /user/hadoop/test.txt
将本地文件系统的uname.txt传到Hadoop分布式文件系统(hdfs)的input目录中。
input就是/user/hadoop/input,要提前创建好:
./bin/hdfs dfs -mkdir input
上传到hdfs上:
./bin/hdfs dfs -put /home/hadoop/test.txt input
下载到本地系统:
./bin/hdfs dfs -get input/uname.txt /home/hadoop/wjx
利用web界面管理HDFS
浏览器打开:http://localhost:50070
利用Java API与HDFS进行交互
打开Eclipse,软件就在/usr/local/eclipse里。
新建工程:
File ->New ->Project ->Java Project
工程名:HDFSExample
添加所需Jar包:
右键项目->Build Path->Add External Archives
为了编写一个能够与HDFS交互的Java应用程序,一般需要向Java工程中添加以下JAR包:
- ”/usr/local/hadoop/share/hadoop/common”目录下的hadoop-common-2.7.1.jar和haoop-nfs-2.7.1.jar;
- /usr/local/hadoop/share/hadoop/common/lib”目录下的所有JAR包;
- “/usr/local/hadoop/share/hadoop/hdfs”目录下的haoop-hdfs-2.7.1.jar和haoop-hdfs-nfs-2.7.1.jar;
- “/usr/local/hadoop/share/hadoop/hdfs/lib”目录下的所有JAR包。
新建类:
右键项目->New->Class
类名称:HDFSFileIfExist,代码如下:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSFileIfExist {
public static void main(String[] args){
try{
String fileName = "test.txt"; //文件在hdfs的用户目录/user/hadoop
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://localhost:9000");
conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
FileSystem fs = FileSystem.get(conf);
if(fs.exists(new Path(fileName))){
System.out.println("文件存在");
}else{
System.out.println("文件不存在");
}
}catch (Exception e){
e.printStackTrace();
}
}
}
运行:Run As -> Java Application
显示“文件不存在”。
创建test文件:
./bin/hdfs dfs -touchz test.txt
再次运行:显示“文件存在”。