Linux下Hadoop hdfs Java API使用

来源:互联网 发布:知乎产品分析 编辑:程序博客网 时间:2024/05/16 12:36

0 前言

搞了大约2天时间终于把Linux下面Java API的使用给弄清楚了。做个笔记方便以后参考。环境如下所示

Hadoop:2.5.1
Linux:Ubuntu kylin
eclipse:luna

1 步骤

首先是要去下载一个eclipse,这里使用的是Luna。名字比较好听,代表月亮消灭你们...
然后发现自带了maven,太棒了!Luna牛掰,毫无疑问创建maven工程,修改pom.xml文件为下面的内容
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  3.   <modelVersion>4.0.0</modelVersion>  
  4.   
  5.   <groupId>maven</groupId>  
  6.   <artifactId>maven</artifactId>  
  7.   <version>0.0.1-SNAPSHOT</version>  
  8.   <packaging>jar</packaging>  
  9.   
  10.   <name>maven</name>  
  11.   <url>http://maven.apache.org</url>  
  12.   
  13.   <properties>  
  14.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  15.   </properties>  
  16.   
  17.   <dependencies>  
  18.     <dependency>  
  19.       <groupId>junit</groupId>  
  20.       <artifactId>junit</artifactId>  
  21.       <version>3.8.1</version>  
  22.       <scope>test</scope>  
  23.     </dependency>  
  24.      <dependency>  
  25.           <groupId>org.apache.hadoop</groupId>  
  26.           <artifactId>hadoop-minicluster</artifactId>  
  27.           <version>2.5.1</version>  
  28.     </dependency>  
  29.     <dependency>  
  30.           <groupId>org.apache.hadoop</groupId>  
  31.           <artifactId>hadoop-client</artifactId>  
  32.           <version>2.5.1</version>  
  33.     </dependency>  
  34.     <dependency>  
  35.           <groupId>org.apache.hadoop</groupId>  
  36.           <artifactId>hadoop-assemblies</artifactId>  
  37.           <version>2.5.1</version>  
  38.     </dependency>  
  39.         <dependency>  
  40.           <groupId>org.apache.hadoop</groupId>  
  41.           <artifactId>hadoop-maven-plugins</artifactId>  
  42.           <version>2.5.1</version>  
  43.     </dependency>  
  44.         <dependency>  
  45.           <groupId>org.apache.hadoop</groupId>  
  46.           <artifactId>hadoop-common</artifactId>  
  47.           <version>2.5.1</version>  
  48.     </dependency>  
  49.         <dependency>  
  50.           <groupId>org.apache.hadoop</groupId>  
  51.           <artifactId>hadoop-hdfs</artifactId>  
  52.           <version>2.5.1</version>  
  53.     </dependency>  
  54.   </dependencies>  
  55. </project>  
然后等待eclipse maven自动下载依赖的包。等啊等就好了,下一步是配置jvm运行的参数,因为运行的时候需要本地的库所以必须配置下。我的Hadoop是放在/home/hadoop-master/hadoop-2.5.1下的。
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. -Djava.library.path=/home/hadoop-master/hadoop-2.5.1/lib/native  
因为hadoop2.5.1自己已经编译好了本地库所以不用在编译一次了(这就是用新不用旧的原因,自己编译太费事儿了。。。。到此一切OK

2 测试代码

是驴子是马,拉出来溜溜。写个小程序跑跑。
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package maven.maven;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.InputStreamReader;  
  11. import java.io.OutputStreamWriter;  
  12. import java.io.Writer;  
  13. import java.util.Date;  
  14.   
  15. import org.apache.hadoop.conf.Configuration;  
  16. import org.apache.hadoop.fs.BlockLocation;  
  17. import org.apache.hadoop.fs.FSDataInputStream;  
  18. import org.apache.hadoop.fs.FSDataOutputStream;  
  19. import org.apache.hadoop.fs.FileStatus;  
  20. import org.apache.hadoop.fs.FileSystem;  
  21. import org.apache.hadoop.fs.Path;  
  22. import org.apache.hadoop.hdfs.DistributedFileSystem;  
  23. import org.apache.hadoop.hdfs.DFSClient.*;  
  24. import org.apache.hadoop.hdfs.protocol.DatanodeInfo;  
  25.   
  26. public class HadoopFSOperations {  
  27.       
  28.     private static Configuration conf = new Configuration();  
  29.     private static final String HADOOP_URL="hdfs://192.168.190.129:9000";  
  30.       
  31.     private static FileSystem fs;  
  32.       
  33.     private static DistributedFileSystem hdfs;  
  34.       
  35.     static {  
  36.         try {  
  37.             FileSystem.setDefaultUri(conf, HADOOP_URL);  
  38.             fs = FileSystem.get(conf);  
  39.             hdfs = (DistributedFileSystem)fs;  
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.     }  
  44.     /** 
  45.      * 列出所有DataNode的名字信息 
  46.      */  
  47.     public void listDataNodeInfo() {          
  48.         try {  
  49.             DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats();  
  50.             String[] names = new String[dataNodeStats.length];  
  51.             System.out.println("List of all the datanode in the HDFS cluster:");  
  52.               
  53.             for (int i=0;i<names.length;i++) {  
  54.                 names[i] = dataNodeStats[i].getHostName();  
  55.                 System.out.println(names[i]);  
  56.             }  
  57.             System.out.println(hdfs.getUri().toString());  
  58.         } catch (Exception e) {  
  59.             e.printStackTrace();  
  60.         }  
  61.     }  
  62.       
  63.     /** 
  64.      * 查看文件是否存在 
  65.      */  
  66.     public void checkFileExist() {  
  67.         try {  
  68.             Path a= hdfs.getHomeDirectory();  
  69.             System.out.println("main path:"+a.toString());  
  70.               
  71.             Path f = new Path("/user/xxx/input01/");  
  72.             boolean exist = fs.exists(f);  
  73.             System.out.println("Whether exist of this file:"+exist);  
  74.               
  75.             //删除文件  
  76. //          if (exist) {  
  77. //              boolean isDeleted = hdfs.delete(f, false);  
  78. //              if(isDeleted) {  
  79. //                  System.out.println("Delete success");  
  80. //              }                 
  81. //          }  
  82.         } catch (Exception e) {  
  83.             e.printStackTrace();  
  84.         }  
  85.     }  
  86.       
  87.     /** 
  88.      *创建文件到HDFS系统上  
  89.      */  
  90.     public void createFile() {  
  91.         try {  
  92.             Path f = new Path("/user/xxx/input02/file01");  
  93.             System.out.println("Create and Write :"+f.getName()+" to hdfs");  
  94.               
  95.             FSDataOutputStream os = fs.create(f, true);  
  96.             Writer out = new OutputStreamWriter(os, "utf-8");//以UTF-8格式写入文件,不乱码  
  97.             out.write("你好 good job");  
  98.             out.close();  
  99.             os.close();  
  100.         } catch (Exception e) {  
  101.             e.printStackTrace();  
  102.         }  
  103.     }  
  104.       
  105.       
  106.     /** 
  107.      * 读取本地文件到HDFS系统<br> 
  108.      * 请保证文件格式一直是UTF-8,从本地->HDFS 
  109.      */  
  110.     public void copyFileToHDFS() {  
  111.         try {  
  112.             Path f = new Path("/user/xxx/input02/file01");  
  113.             File file = new File("E:\\hadoopTest\\temporary.txt");  
  114.               
  115.             FileInputStream is = new FileInputStream(file);  
  116.             InputStreamReader isr = new InputStreamReader(is, "utf-8");  
  117.             BufferedReader br = new BufferedReader(isr);  
  118.               
  119.             FSDataOutputStream os = fs.create(f, true);  
  120.             Writer out = new OutputStreamWriter(os, "utf-8");  
  121.               
  122.             String str = "";  
  123.             while((str=br.readLine()) != null) {  
  124.                 out.write(str+"\n");  
  125.             }  
  126.             br.close();  
  127.             isr.close();  
  128.             is.close();  
  129.             out.close();  
  130.             os.close();  
  131.             System.out.println("Write content of file "+file.getName()+" to hdfs file "+f.getName()+" success");  
  132.         } catch (Exception e) {  
  133.             e.printStackTrace();  
  134.         }  
  135.     }  
  136.       
  137.     /** 
  138.      * 取得文件块所在的位置.. 
  139.      */  
  140.     public void getLocation() {  
  141.         try {  
  142.             Path f = new Path("/user/xxx/input02/file01");  
  143.             FileStatus fileStatus = fs.getFileStatus(f);  
  144.               
  145.             BlockLocation[] blkLocations = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());  
  146.             for (BlockLocation currentLocation : blkLocations) {  
  147.                 String[] hosts = currentLocation.getHosts();  
  148.                 for (String host : hosts) {  
  149.                     System.out.println(host);  
  150.                 }  
  151.             }  
  152.               
  153.             //取得最后修改时间  
  154.             long modifyTime = fileStatus.getModificationTime();  
  155.             Date d = new Date(modifyTime);  
  156.             System.out.println(d);  
  157.         } catch (Exception e) {  
  158.             e.printStackTrace();  
  159.         }  
  160.     }  
  161.       
  162.     /** 
  163.      * 读取hdfs中的文件内容 
  164.      */  
  165.     public void readFileFromHdfs() {  
  166.         try {  
  167.             Path f = new Path("/user/xxx/input02/file01");  
  168.               
  169.             FSDataInputStream dis = fs.open(f);  
  170.             InputStreamReader isr = new InputStreamReader(dis, "utf-8");  
  171.             BufferedReader br = new BufferedReader(isr);  
  172.             String str = "";  
  173.             while ((str = br.readLine()) !=null) {  
  174.                 System.out.println(str);  
  175.             }  
  176.             br.close();  
  177.             isr.close();  
  178.             dis.close();  
  179.         } catch (Exception e) {  
  180.             e.printStackTrace();  
  181.         }  
  182.     }  
  183.       
  184.     /** 
  185.      * list all file/directory 
  186.      * @param args 
  187.      * @throws IOException  
  188.      * @throws IllegalArgumentException  
  189.      * @throws FileNotFoundException  
  190.      */  
  191.     public void listFileStatus(String path) throws FileNotFoundException, IllegalArgumentException, IOException {  
  192.         FileStatus fileStatus[]=fs.listStatus(new Path(path));  
  193.         int listlength=fileStatus.length;  
  194.         for (int i=0 ;i<listlength ;i++){  
  195.             if (fileStatus[i].isDirectory() == false) {  
  196.                 System.out.println("filename:"  
  197.                         + fileStatus[i].getPath().getName() + "\tsize:"  
  198.                         + fileStatus[i].getLen());  
  199.             } else {  
  200.                 String newpath = fileStatus[i].getPath().toString();  
  201.                 listFileStatus(newpath);  
  202.             }  
  203.         }  
  204.     }  
  205.       
  206.     public static void main(String[] args) {  
  207.         HadoopFSOperations a = new HadoopFSOperations();  
  208.         a.listDataNodeInfo();  
  209. //      a.checkFileExist();  
  210. //      a.createFile();  
  211. //      a.copyFileToHDFS();  
  212. //      a.getLocation();  
  213. //      a.readFileFromHdfs();  
  214.         try {  
  215.             a.listFileStatus(HADOOP_URL+"/user");  
  216.         } catch (FileNotFoundException e) {  
  217.             // TODO Auto-generated catch block  
  218.             e.printStackTrace();  
  219.         } catch (IllegalArgumentException e) {  
  220.             // TODO Auto-generated catch block  
  221.             e.printStackTrace();  
  222.         } catch (IOException e) {  
  223.             // TODO Auto-generated catch block  
  224.             e.printStackTrace();  
  225.         }  
  226.     }  
  227. }  

因为我的hadoop是在192.168.190.129上的所以private static final String HADOOP_URL="hdfs://192.168.190.129:9000";,请酌情修改。搞定跑起来,就能看到下面的结果

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. List of all the datanode in the HDFS cluster:  
  2. hadoopslaver0  
  3. hadoopslaver2  
  4. hadoopslaver1  
  5. hdfs://192.168.190.129:9000  
  6. filename:TrustCom2015_CFP.pdf   size:290401  
  7. filename:jd.PNG size:16647  

可以看到 三个datanode hadoopslaver0,1,2 以及/user下事先放好的文件。小实验成功

3 总结

在Linux下面Java API就可以按照上面的步骤弄起来了。总算是万里之行迈出了第一步。
0 0