HDFS文件操作

hdfs 文件操作,使用FileSystem里提供的方法实现。代码:
[java]  view plain copy
  1. package hdfs.fs.nefu;  
  2.   
  3. import java.io.IOException;  
  4. import org.apache.hadoop.conf.Configuration;  
  5. import org.apache.hadoop.fs.BlockLocation;  
  6. import org.apache.hadoop.fs.FSDataOutputStream;  
  7. import org.apache.hadoop.fs.FileStatus;  
  8. import org.apache.hadoop.fs.FileSystem;  
  9. import org.apache.hadoop.fs.Path;  
  10. import org.apache.hadoop.hdfs.DistributedFileSystem;  
  11. import org.apache.hadoop.hdfs.protocol.DatanodeInfo;  
  12.   
  13. public class hdfsFileOperation {  
  14.       
  15.     public static void main(String[] args) throws IOException {  
  16.     /*HDFS文件操作 主要是通过已有的方法来进行实现 
  17.      * @param 1.获取configuration对象 
  18.      * @param 2.获取FileSystem对象 
  19.      * @param 3.进行文件操作 
  20.      * */  
  21.         //创建文件  
  22.         createFiles();  
  23.         //创建目录  
  24.         createDir();  
  25.         //重命名文件  
  26.         fileRename();  
  27.         //删除文件  
  28.         deleteFile();  
  29.         //上传文件  
  30.         uploadFile();  
  31.         //查看文件是否存在  
  32.         fileExists();  
  33.         //查看文件最后修改时间  
  34.         fileModifyTime();  
  35.         //查看目录下的所有文件  
  36.         showFile();  
  37.         //查看文件所在位置  
  38.         showLocation();  
  39.         //获取集群的名称节点  
  40.         showDatanodeName();  
  41.     }  
  42.   
  43.     private static void showDatanodeName() throws IOException {  
  44.         Configuration conf = new Configuration();  
  45.         FileSystem file = FileSystem.get(conf);  
  46.         DistributedFileSystem hdfs = (DistributedFileSystem)file;  
  47.         //获取各个节点信息  
  48.         DatanodeInfo[] datanodeStatus = hdfs.getDataNodeStats();  
  49.         for(int i=0;i<datanodeStatus.length;i++){  
  50.             System.out.println("datanode_name:"+datanodeStatus[i].getHostName());  
  51.         }  
  52.     }  
  53.   
  54.     private static void showLocation() throws IOException {  
  55.         Configuration conf = new Configuration();  
  56.         FileSystem file = FileSystem.get(conf);  
  57.       
  58.         Path dest = new Path("/usr/hadoop/hello");  
  59.           
  60.         FileStatus filestatus = file.getFileStatus(dest);  
  61.         //获取文件块信息  
  62.         BlockLocation[] location = file.getFileBlockLocations(filestatus, 0, filestatus.getLen());  
  63.         //可存在多个节点  
  64.         int length = location.length;  
  65.         for(int i=0;i<length;i++){  
  66.             /*@param getHosts:Get the list of hosts (hostname) hosting this block return String*/  
  67.             String[] host = location[i].getHosts();  
  68.             System.out.println("block_"+i+host[0]);  
  69.         }  
  70.     }  
  71.   
  72.     private static void showFile() throws IOException {  
  73.         Configuration conf = new Configuration();  
  74.         FileSystem file = FileSystem.get(conf);  
  75.       
  76.         Path dest = new Path("/");  
  77.           
  78.         FileStatus files[] = file.listStatus(dest);  
  79.         //显示文件  
  80.         for(int i=0;i<files.length;i++){  
  81.             System.out.println(files[i].getPath().toString());  
  82.         }  
  83.     }  
  84.   
  85.     private static void fileModifyTime() throws IOException {  
  86.         Configuration conf = new Configuration();  
  87.         FileSystem fs = FileSystem.get(conf);  
  88.           
  89.         Path path = new Path("hdfs://localhost/hello/text.txt");  
  90.         //获取文件信息  
  91.         FileStatus fstatus = fs.getFileStatus(path);  
  92.         //获取修改时间  
  93.         long modify_time = fstatus.getModificationTime();  
  94.         System.out.println("文件修改时间"+modify_time);  
  95.     }  
  96.   
  97.     private static void fileExists() throws IOException {  
  98.         Configuration conf = new Configuration();  
  99.         FileSystem fs = FileSystem.get(conf);  
  100.         Path path = new Path("/test2");  
  101.         boolean isExists = fs.exists(path);  
  102.         System.out.println(isExists?"文件存在":"文件不存在");  
  103.     }  
  104.   
  105.     private static void uploadFile() throws IOException {  
  106.         Configuration conf = new Configuration();  
  107.         FileSystem file = FileSystem.get(conf);  
  108.           
  109.         //本地文件 在java api中文件名都是字符串,而在hadoop中的文件名都是path对象  
  110.         Path src = new Path("D:\\log.txt");  
  111.           
  112.         //HDFS文件   
  113.         Path dest = new Path("/");  
  114.           
  115.         file.copyFromLocalFile(src, dest);  
  116.         System.out.println("Upload to "+conf.get("fs.default.name"));  
  117.           
  118.         //获取文件信息  
  119.         FileStatus files[] = file.listStatus(dest);  
  120.           
  121.         //输出信息  
  122.         for(FileStatus value:files){  
  123.             System.out.println(value.getPath());  
  124.         }  
  125.     }  
  126.   
  127.     private static void deleteFile() throws IOException {  
  128.         Configuration conf = new Configuration();  
  129.         FileSystem fs = FileSystem.get(conf);  
  130.         Path path =  new Path("/test1");  
  131.         /** 
  132.          * @param path 待删除的文件 
  133.          * @param false :if path is a directory and set to true,  
  134.          * the directory is deleted else throws an exception.  
  135.          * In case of a file the recursive can be set to either true or false.  
  136.          * */  
  137.         fs.delete(path, false);  
  138.     }  
  139.   
  140.     private static void fileRename() throws IOException {  
  141.         Configuration conf = new Configuration();  
  142.         FileSystem fs = FileSystem.get(conf);  
  143.           
  144.         Path file1 = new Path("/test1");  
  145.         Path file2 = new Path("/test2");  
  146.         boolean isRename = fs.rename(file1, file2);  
  147.           
  148.         System.out.println(isRename?"已经重命名":"未被重命名");  
  149.     }  
  150.   
  151.     private static void createDir() throws IOException {  
  152.         Configuration conf = new Configuration();  
  153.         FileSystem fs = FileSystem.get(conf);  
  154.           
  155.         Path dst = new Path("hdfs://localhost/hello/Dir");  
  156.         fs.mkdirs(dst);  
  157.     }  
  158.     private static void createFiles() throws IOException {  
  159.         Configuration conf = new Configuration();  
  160.         FileSystem fs = FileSystem.get(conf);  
  161.           
  162.         Path dst = new Path("hdfs://localhost/hello");  
  163.           
  164.         //文件内容 字节数组  
  165.         byte[] buffer ="hello xd".getBytes();  
  166.         //创建文件是一个输出流  
  167.         FSDataOutputStream output = fs.create(dst);  
  168.         //写入  
  169.         output.write(buffer,0,buffer.length);  
  170.     }  
  171. }  

实现:在输入目录下的所有文件中,检索给定的字符串所出现的行,并将这些行的内容输出到本地文件系统的输出文件夹中。

shell:hadoop jar  resultFilter.jar resultFilter <dfs path> <local path> <match string> <file lines num>

[java]  view plain copy
  1. package hdfs.fs.nefu;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.Scanner;  
  6. import org.apache.hadoop.conf.Configuration;  
  7. import org.apache.hadoop.fs.FSDataInputStream;  
  8. import org.apache.hadoop.fs.FSDataOutputStream;  
  9. import org.apache.hadoop.fs.FileStatus;  
  10. import org.apache.hadoop.fs.FileSystem;  
  11. import org.apache.hadoop.fs.Path;  
  12.   
  13. public class resultFilter {  
  14.   
  15.     public static void main(String[] args) throws IOException {  
  16.         // TODO Auto-generated method stub  
  17.         Configuration conf = new Configuration();  
  18.         FileSystem fs = FileSystem.get(conf);  
  19.         FileSystem local = FileSystem.getLocal(conf);//本地文件系统实例  
  20.         Path inputdir,localdir; //hdfs上的路径 ,本地路径  
  21.           
  22.         FileStatus inputFiles[];    //记录文件信息  
  23.         FSDataOutputStream output = null;   //创建文件的时候 需要输出流  
  24.         FSDataInputStream input = null;     //打开文件的时候 需要输入流  
  25.         /* 
  26.          * @param scanner:一个可以使用正则表达式来分析基本类型和字符串的 简单文本扫描器。  
  27.          * Scanner 使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配。 
  28.          * 然后可以使用不同的 next 方法将得到的标记转换为不同类型的值。  
  29.          * */  
  30.         Scanner scan;  
  31.         String str;//待匹配的字符串  
  32.         byte[] buffer;  
  33.         int singleFileLines;  
  34.         int numLines,i,numFiles;  
  35.           
  36.         if(args.length!=4){  
  37.             System.err.println("usage resultFilter<dst path><local path>"+  
  38.                                 "<match str><single file lines>");  
  39.             return;  
  40.         }  
  41.         inputdir = new Path(args[0]);  
  42.         //从输入处 获得每个文件的限制行数  
  43.         singleFileLines = Integer.parseInt(args[3]);  
  44.           
  45.         try{  
  46.             inputFiles = fs.listStatus(inputdir);//获取目录信息  
  47.             numLines = 0;  
  48.             numFiles = 1;  
  49.             localdir = new Path(args[1]);  
  50.             //若目标路径存在 就删除文件  
  51.             if(local.exists(localdir)){  
  52.                 local.delete(localdir, true);  
  53.             }  
  54.             for(i=0;i<inputFiles.length;i++){  
  55.                 if(inputFiles[i].isDir() == true){  
  56.                     continue;  
  57.                 }  
  58.                 //输出文件名  
  59.                 System.out.println(inputFiles[i].getPath().getName());  
  60.                 //打开文件 投入输入流中  
  61.                 input = fs.open(inputFiles[i].getPath());  
  62.                 //从输入流 扫描  
  63.                 scan = new Scanner(input);  
  64.                   
  65.                 while(scan.hasNext()){  
  66.                     str = scan.nextLine();  
  67.                     if(str.indexOf(args[2])==-1){  
  68.                         continue;  
  69.                     }  
  70.                     numLines++;  
  71.                     //如果是1 需要创建文件  
  72.                     if(numLines == 1){  
  73.                         /*@param File.separator:系统默认的分隔符 windows:\\ unix,linux:/*/  
  74.                         localdir = new Path(args[1]+File.separator+numLines);  
  75.                         output = local.create(localdir);  
  76.                         numFiles++;  
  77.                     }  
  78.                     buffer = (str+"\n").getBytes();//字符串转化为字符数组  
  79.                     output.write(buffer,0,buffer.length);  
  80.                     //达到设定的文件行数的上限  
  81.                     if(numLines == singleFileLines){  
  82.                         output.close();  
  83.                         numLines = 0;  
  84.                     }  
  85.                 }  
  86.                 //关闭流  
  87.                     scan.close();  
  88.                     input.close();  
  89.             }  
  90.             if(output != null){  
  91.                 output.close();  
  92.             }  
  93.         }catch(Exception e){  
  94.             e.printStackTrace();  
  95.         }  
  96.     }  
  97. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值