java对HDFS中文件的操作——FileSystem

1 概述:

1   1     Hadoop 提供一类api可以通过java工程操作hdfs中的文件,包括:文件打开,读写,删除等、

           目录的创建,删除,读取目录中所有文件等。

2   2    需要处理hadoop的文件程序需要引入下面jar包,可以hadoop-1.2.1\lib找到。

     hadoop-core和common-log,commons-configuration-1.6.jar,commons-lang-2.4.jar。

 

3  3 想要运行写好的程序操作hdfs中文件两种方法:1 安装elipse的hadoop插件(之前有介绍)  2、将写好成程序打成jar包,在服务器上用hadoop命令运行

 

4  4  程序处理步骤: 1) 得到Configuration对象2)得到FileSystem对象 3)进行文件操作。

 

    5 以下是操作文件的事例程序,版本 hadoop-1.2.1

 

Java代码  收藏代码

  1. package org.tony.hdfs;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.hadoop.conf.Configuration;  
  6. import org.apache.hadoop.fs.FSDataInputStream;  
  7. import org.apache.hadoop.fs.FSDataOutputStream;  
  8. import org.apache.hadoop.fs.FileStatus;  
  9. import org.apache.hadoop.fs.FileSystem;  
  10. import org.apache.hadoop.fs.Path;  
  11.   
  12.   
  13. public class HDFSTest {  
  14.     public static void main(String[] args) throws Exception  
  15.     {  
  16.         //uploadLocalFile2HDFS("E:/1.txt","/tmp/1.txt");//E盘下文件传到hdfs上  
  17.         //createNewHDFSFile("/tmp/create2", "hello");  
  18.         //String str = new String(readHDFSFile("/tmp/create2"));  
  19.         //System.out.println(str);  
  20.           
  21.         //mkdir("/tmp/testdir");  
  22.         //deleteDir("/tmp/testdir");  
  23.         //listAll("/tmp/");  
  24.                 getDateNodeHost();  
  25.     }  
  26.     //获取HDFS集群上所有节点名称信息  
  27.     public static void getDateNodeHost() throws IOException{  
  28.           
  29.         Configuration conf = getConf();  
  30.   
  31.                FileSystem fs=FileSystem.get(conf);  
  32.                DistributedFileSystem hdfs = (DistributedFileSystem)fs;  
  33.                DatanodeInfo[] dataNodeStats = hdfs.getDataNodeStats();  
  34.                for(int i=0;i<dataNodeStats.length;i++){  
  35.                   System.out.println("DataNode_"+i+"_Name:"+dataNodeStats[i].getHostName());  
  36.                }  
  37.     }  
  38.     /* 
  39.      * upload the local file to the hds  
  40.      * 路径是全路径 
  41.      */  
  42.     public static void uploadLocalFile2HDFS(String s, String d)   
  43.         throws IOException  
  44.     {  
  45.         Configuration conf = getConf();  
  46.         FileSystem hdfs = FileSystem.get(conf);  
  47.         Path src = new Path(s);  
  48.         Path dst = new Path(d);  
  49.         hdfs.copyFromLocalFile(src, dst);  
  50.         hdfs.close();  
  51.     }  
  52.       
  53.     /* 
  54.      * create a new file in the hdfs. 
  55.      * notice that the toCreateFilePath is the full path 
  56.      * and write the content to the hdfs file. 
  57.      */  
  58.     public static void createNewHDFSFile(String toCreateFilePath, String content) throws IOException  
  59.     {  
  60.         Configuration conf = getConf();  
  61.         FileSystem hdfs = FileSystem.get(conf);  
  62.           
  63.         FSDataOutputStream os = hdfs.create(new Path(toCreateFilePath));  
  64.         os.write(content.getBytes("UTF-8"));  
  65.         os.close();  
  66.         hdfs.close();  
  67.     }  
  68.       
  69.     /* 
  70.      * delete the hdfs file  
  71.      * notice that the dst is the full path name 
  72.      */  
  73.     public static boolean deleteHDFSFile(String dst) throws IOException  
  74.     {  
  75.         Configuration conf = getConf();  
  76.         FileSystem hdfs = FileSystem.get(conf);  
  77.           
  78.         Path path = new Path(dst);  
  79.         boolean isDeleted = hdfs.delete(path);  
  80.         hdfs.close();  
  81.         return isDeleted;  
  82.     }  
  83.       
  84.       
  85.     /* 
  86.      * read the hdfs file content 
  87.      * notice that the dst is the full path name 
  88.      */  
  89.     public static byte[] readHDFSFile(String dst) throws Exception  
  90.     {  
  91.         Configuration conf = getConf();  
  92.         FileSystem fs = FileSystem.get(conf);  
  93.           
  94.         // check if the file exists  
  95.         Path path = new Path(dst);  
  96.         if ( fs.exists(path) )  
  97.         {  
  98.             FSDataInputStream is = fs.open(path);  
  99.             // get the file info to create the buffer  
  100.             FileStatus stat = fs.getFileStatus(path);  
  101.             // create the buffer  
  102.             byte[] buffer = new byte[Integer.parseInt(String.valueOf(stat.getLen()))];  
  103.             is.readFully(0, buffer);  
  104.               
  105.             is.close();  
  106.             fs.close();  
  107.               
  108.             return buffer;  
  109.         }  
  110.         else  
  111.         {  
  112.             throw new Exception("the file is not found .");  
  113.         }  
  114.     }  
  115.       
  116.       
  117.     /* 
  118.      * make a new dir in the hdfs 
  119.      * the dir may like '/tmp/testdir' 
  120.      */  
  121.     public static void mkdir(String dir) throws IOException  
  122.     {  
  123.         Configuration conf = getConf();  
  124.         FileSystem fs = FileSystem.get(conf);  
  125.         fs.mkdirs(new Path(dir));  
  126.           
  127.         fs.close();  
  128.     }  
  129.       
  130.     /* 
  131.      * delete a dir in the hdfs 
  132.      * dir may like '/tmp/testdir' 
  133.      */  
  134.     public static void deleteDir(String dir) throws IOException  
  135.     {  
  136.         Configuration conf = getConf();  
  137.         FileSystem fs = FileSystem.get(conf);  
  138.         fs.delete(new Path(dir));  
  139.         fs.close();  
  140.     }  
  141.     //文件系统连接到 hdfs的配置信息   
  142.     private static Configuration getConf(){  
  143.         Configuration conf = new Configuration();  
  144.         // 这句话很关键,这些信息就是hadoop配置文件中的信息  
  145.         conf.set("mapred.job.tracker""192.168.102.136:9001");  
  146.         conf.set("fs.default.name""hdfs://192.168.102.136:9000");  
  147.         return conf;  
  148.     }  
  149.       
  150.     /** 
  151.     * @Title: listAll  
  152.     * @Description: 列出目录下所有文件  
  153.     * @return void    返回类型  
  154.     * @throws 
  155.      */  
  156.     public static void listAll(String dir) throws IOException  
  157.     {  
  158.         Configuration conf = getConf();  
  159.         FileSystem fs = FileSystem.get(conf);  
  160.         FileStatus[] stats = fs.listStatus(new Path(dir));  
  161.         for(int i = 0; i < stats.length; ++i)  
  162.         {  
  163.             if (!stats[i].isDir())  
  164.             {  
  165.                 // regular file  
  166.                 System.out.println(stats[i].getPath().toString());  
  167.             }  
  168.             else   
  169.             {  
  170.                 // dir  
  171.                 System.out.println(stats[i].getPath().toString());  
  172.             }  
  173. //          else if(stats[i].())  
  174. //          {  
  175. //              // is s symlink in linux  
  176. //              System.out.println(stats[i].getPath().toString());  
  177. //          }  
  178.                   
  179.         }  
  180.         fs.close();  
  181.     }  
  182.       
  183. }  

 

 注意:因为hadoop读写文件时候需要权限,如果你window用户名为admin而hadoop集群中目录权限是hadoop用户,读写会失败

  1 修改window系统用户为hadoop

  2 elipse运行的jvm参数中设置 -DHADOOP_USER_NAME=hadoop ,运行的用户为hadoop 

  3 部署一个linux环境,在linux环境中开发是比较容易的(用户问题容易设置)。

  4 运行的时候指定用户 ,如下:

   Configuration conf = new Configuration();

FileSystem hdfs = FileSystem.get(new URI("hdfs://192.168.142.133:9000"),conf,"hadoop");

 

原文http://username2.iteye.com/blog/2158925

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值