第一個hadoop程式(java程式訪問hadoop的hdfs檔案系統中的檔案)
1:hadoop2.7.3環境
2:阿里雲伺服器centos6.5,ip是:47.88.14.190
3:hadoop在偽分散式下執行的。
4:具體配置檔案如下:
1)core-site.xml配置(ip地址最好不用localhost,不然不好測試)
<configuration>
<property>
<name>fs.defaultFS</name>
<value>hdfs://47.88.14.190:9000</value>
</property>
</configuration>
2)hdfs-site.xml配置(配置副本為1,也就是偽分散式)
<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
</configuration>
3)mapred-site.xml
<configuration>
<property>
<name>mapred.job.tracker</name>
<value>47.88.14.190:8021</value>
</property>
</configuration>
5:注意,4中的配置檔案的埠號很重要,因為java程式訪問hadoop的時候就要用這些埠。
6:執行hadoop,執行sbin/start-all.sh
7:在centos6.5中執行,hadoop fs -mkdir /test
8:上傳test.txt到hadoop的檔案系統中去, hadoop fs -copyFromLocal /usr/text.txt /test
9:新建一個java程式,讀取hadoop檔案系統中的/test/text.txt檔案。(注意埠號9000就是core-site.xml中配置的埠號)
import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; public class FileSystemCat { public static void main(String[] args) throws Exception { String uri="hdfs://47.88.14.190:9000/test/test.txt"; Configuration configuration=new Configuration(); FileSystem fileSystem=FileSystem.get(URI.create(uri), configuration); FSDataInputStream in=null; in=fileSystem.open(new Path(uri)); // FileStatus fileStatus=fileSystem.getFileStatus(new Path(uri)); // byte[] buffer=new byte[1024]; // in.read(4096, buffer, 0, 1024); IOUtils.copyBytes(in, System.out, 4096, false); IOUtils.closeStream(in); } }
10:jar包問題,很多人,將我上面的程式碼拷貝到自己的eclipse中,發現缺少了jar,然後問題來了,我們需要匯入哪些jar包呢?
我的建議是初學者安裝hadoop-eclipse-plugins-2.7.3.jar外掛,這個外掛網上可以下載,安裝後,可以直接右鍵新建Map/Reduce工程,自動幫我們匯入hadoop開發需要的相關jar包,這樣就不存在ClassNotFound異常了。