HDFS CRUD 操作

1 查找

列出某个目录下的文件名称,hdfs命令如下所示:

hdfs dfs –ls/usr/app

java代码片段:

[plain] view plain copy print ?
  1. public void list(String srcPath) {  
  2.            Configuration conf = new Configuration();  
  3.            LOG.info("[Defaultfs] :" +conf.get("fs.default.name"));  
  4.          conf.set("hadoop.job.ugi","app,app");   //It is not necessary for the default user.  
  5.            FileSystem fs;  
  6.           try {  
  7.                    fs= FileSystem.get(conf);  
  8.                    RemoteIterator<LocatedFileStatus>rmIterator = fs.listLocatedStatus(new Path(srcPath));  
  9.                    while (rmIterator.hasNext()) {  
  10.                              Path path = rmIterator.next().getPath();  
  11.                              if(fs.isDirectory(path)){  
  12.                                        LOG.info("-----------DirectoryName: "+path.getName());  
  13.                              }  
  14.                              else if(fs.isFile(path)){  
  15.                                        LOG.info("-----------FileName: "+path.getName());  
  16.                              }  
  17.                    }  
  18.           }catch (IOException e) {  
  19.                    LOG.error("list fileSysetm object stream.:" , e);  
  20.                    new RuntimeException(e);  
  21.           }  
  22. }  


输出结果:

2014-03-11 22:38:15,329 INFO  (com.hdfs.client.SyncDFS:48) ------------File Name: README.txt

2014-03-11 22:38:15,331 INFO  (com.hdfs.client.SyncDFS:45) ------------Directory Name: blog_blogpost

2014-03-11 22:38:15,333 INFO  (com.hdfs.client.SyncDFS:45) ------------Directory Name: test

读取文件中的内容,hdfs命令如下:

hdfs dfs –cat /input

java 代码:

[plain] view plain copy print ?
  1. public void readFile(String file){  
  2.            Configurationconf = new Configuration();  
  3.            FileSystemfs;  
  4.            try {  
  5.                     fs= FileSystem.get(conf);  
  6.                     Pathpath = new Path(file);  
  7.                     if(!fs.exists(path)){  
  8.                              LOG.warn("file'"+ file+"' doesn't exist!");  
  9.                              return ;  
  10.                     }  
  11.                     FSDataInputStreamin = fs.open(path);  
  12.                     Stringfilename = file.substring(file.lastIndexOf('/') + 1, file.length());  
  13.                     OutputStreamout = new BufferedOutputStream(new FileOutputStream(  
  14.                                                                    new File(filename)));  
  15.   
  16.                     byte[] b = new byte[1024];  
  17.                     int numBytes = 0;  
  18.                     while ((numBytes = in.read(b)) > 0) {  
  19.                              out.write(b,0, numBytes);  
  20.                     }  
  21.                     in.close();  
  22.                     out.close();  
  23.                     fs.close();  
  24.            }catch (IOException e) {  
  25.                     LOG.error("ifExists fs Exception caught! :" , e);  
  26.                     new RuntimeException(e);  
  27.            }  
  28.  }  


获取文件的修改时间,java代码:

[plain] view plain copy print ?
  1. /**  
  2.         * Gets the information about the file modifiedtime.  
  3.         * @param source  
  4.         * @throws IOException  
  5.         */  
  6.        public void getModificationTime(String source) throws IOException{  
  7.                     
  8.                  Configurationconf = new Configuration();  
  9.                     
  10.                  FileSystemfs = FileSystem.get(conf);  
  11.                  PathsrcPath = new Path(source);  
  12.                     
  13.                  // Check if the file alreadyexists  
  14.                  if (!(fs.exists(srcPath))) {  
  15.                  System.out.println("No such destination " + srcPath);  
  16.                  return;  
  17.                  }  
  18.                  // Get the filename out of thefile path  
  19.                  Stringfilename = source.substring(source.lastIndexOf('/') + 1, source.length());  
  20.                     
  21.                  FileStatusfileStatus = fs.getFileStatus(srcPath);  
  22.                  long modificationTime =fileStatus.getModificationTime();  
  23.                     
  24.                  LOG.info("modified datetime: " + System.out.format("File %s; Modification time : %0.2f%n",filename,modificationTime));  
  25.                     
  26.        }  


获取文件块定位信息,java代码:

[plain] view plain copy print ?
  1. /**  
  2.           * Gets the file block location info  
  3.           * @param source  
  4.           * @throws IOException  
  5.           */  
  6.          public void getBlockLocations(String source) throws IOException{  
  7.                    Configurationconf = new Configuration();  
  8.                    FileSystemfs = FileSystem.get(conf);  
  9.                    PathsrcPath = new Path(source);  
  10.                       
  11.                    // Check if the file alreadyexists  
  12.                    if (!(ifExists(source))) {  
  13.                             System.out.println("No such destination " + srcPath);  
  14.                             return;  
  15.                    }  
  16.                    // Get the filename out of thefile path  
  17.                    Stringfilename = source.substring(source.lastIndexOf('/') + 1, source.length());  
  18.                       
  19.                    FileStatusfileStatus = fs.getFileStatus(srcPath);  
  20.                       
  21.                    BlockLocation[]blkLocations = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());  
  22.                    int blkCount = blkLocations.length;  
  23.                       
  24.                    System.out.println("File :" + filename + "stored at:");  
  25.                    for (int i=0; i < blkCount; i++) {  
  26.                             String[]hosts = blkLocations[i].getHosts();  
  27.                             LOG.info("host ip:" +System.out.format("Host %d: %s %n", i, hosts));  
  28.                    }  
  29.          }  


获取Hadoop集群中data node的DNS主机名,java代码:

[plain] view plain copy print ?
  1. public void getHostnames () throwsIOException{  
  2.                    Configurationconfig = new Configuration();  
  3.                     
  4.                    FileSystemfs = FileSystem.get(config);  
  5.                    DistributedFileSystemhdfs = (DistributedFileSystem) fs;  
  6.                    DatanodeInfo[]dataNodeStats = hdfs.getDataNodeStats();  
  7.                       
  8.                    String[]names = new String[dataNodeStats.length];  
  9.                    for (int i = 0; i < dataNodeStats.length; i++) {  
  10.                             names[i]= dataNodeStats[i].getHostName();  
  11.                             LOG.info("datenode hostname:"+(dataNodeStats[i].getHostName()));  
  12.                    }  
  13.          }  


 

2 创建

创建一个目录,指定具体的文件路径。hdfs命令如下:

[plain] view plain copy print ?
  1. hdfs dfs –mkdir/usr/app/tmp  


java代码:

       

[java] view plain copy print ?
  1. public void mkdir(String dir){  
  2.                  Configurationconf = new Configuration();  
  3.                  FileSystemfs = null;  
  4.                  try {  
  5.                           fs= FileSystem.get(conf);  
  6.                           Pathpath = new Path(dir);  
  7.                           if(!fs.exists(path)){  
  8.                                    fs.mkdirs(path);  
  9.                                    LOG.debug("create directory '"+dir+"' successfully!");  
  10.                           }else{  
  11.                                    LOG.debug("directory '"+dir+"' exits!");  
  12.                           }  
  13.                  }catch (IOException e) {  
  14.                           LOG.error("FileSystem get configuration with anerror");  
  15.                           e.printStackTrace();  
  16.                  }finally{  
  17.                           if(fs!= null){  
  18.                                    try {  
  19.                                              fs.close();  
  20.                                    }catch (IOException e) {  
  21.                                              LOG.error("close fs object stream. :" , e);  
  22.                                              new RuntimeException(e);  
  23.                                    }  
  24.                           }  
  25.                  }  
  26.        }  

将本地文件上传到hdfs上去,java代码如下:

[plain] view plain copy print ?
  1. public void copyFromLocal (String source, String dest) {  
  2.                       
  3.                    Configurationconf = new Configuration();  
  4.                    FileSystemfs;  
  5.                    try {  
  6.                             fs= FileSystem.get(conf);  
  7.                             PathsrcPath = new Path(source);  
  8.                                
  9.                             PathdstPath = new Path(dest);  
  10.                             // Check if the file alreadyexists  
  11.                             if (!(fs.exists(dstPath))) {  
  12.                                      LOG.warn("dstPathpath doesn't exist" );  
  13.                                      LOG.error("No such destination " + dstPath);  
  14.                                      return;  
  15.                             }  
  16.                                
  17.                             // Get the filename out of thefile path  
  18.                             Stringfilename = source.substring(source.lastIndexOf('/') + 1, source.length());  
  19.                                
  20.                             try{  
  21.                                      //if the file exists in thedestination path, it will throw exception.  
  22. //                                   fs.copyFromLocalFile(srcPath,dstPath);  
  23.                                      //remove and overwrite files withthe method  
  24.                                      //copyFromLocalFile(booleandelSrc, boolean overwrite, Path src, Path dst)  
  25.                                      fs.copyFromLocalFile(false, true, srcPath, dstPath);  
  26.                                      LOG.info("File " + filename + "copied to " + dest);  
  27.                             }catch(Exception e){  
  28.                                      LOG.error("copyFromLocalFile exception caught!:" , e);  
  29.                                      new RuntimeException(e);  
  30.                             }finally{  
  31.                                      fs.close();  
  32.                             }  
  33.                    }catch (IOException e1) {  
  34.                             LOG.error("copyFromLocal IOException objectstream. :" ,e1);  
  35.                             new RuntimeException(e1);  
  36.                    }  
  37.          }  


        

添加一个文件到指定的目录下,java代码如下:

      

[java] view plain copy print ?
  1. public void addFile(String source, String dest)  {  
  2.                          // Conf object will readthe HDFS configuration parameters  
  3.                          Configurationconf = new Configuration();  
  4.                          FileSystemfs;  
  5.                          try {  
  6.                                   fs= FileSystem.get(conf);  
  7.                                   // Get the filename out of thefile path  
  8.                                   Stringfilename = source.substring(source.lastIndexOf('/') + 1, source.length());  
  9.                                    
  10.                                   // Create the destination pathincluding the filename.  
  11.                                   if (dest.charAt(dest.length() - 1) != '/') {  
  12.                                             dest= dest + "/" + filename;  
  13.                                   }else {  
  14.                                             dest= dest + filename;  
  15.                                   }  
  16.                                    
  17.                                   // Check if the file alreadyexists  
  18.                                   Pathpath = new Path(dest);  
  19.                                   if (fs.exists(path)) {  
  20.                                             LOG.error("File " + dest + " already exists");  
  21.                                             return;  
  22.                                   }  
  23.                                    
  24.                                   // Create a new file and writedata to it.  
  25.                                   FSDataOutputStreamout = fs.create(path);  
  26.                                   InputStreamin = new BufferedInputStream(new FileInputStream(  
  27.                                                                                                                                                   new File(source)));  
  28.                                    
  29.                                   byte[] b = new byte[1024];  
  30.                                   int numBytes = 0;  
  31.                                   //In this way read and write datato destination file.  
  32.                                   while ((numBytes = in.read(b)) > 0) {  
  33.                                             out.write(b,0, numBytes);  
  34.                                   }  
  35.                                   in.close();  
  36.                                   out.close();  
  37.                                   fs.close();  
  38.                          }catch (IOException e) {  
  39.                                   LOG.error("addFile Exception caught! :" , e);  
  40.                                   new RuntimeException(e);  
  41.                          }  
  42.       }  


3 修改

重新命名hdfs中的文件名称,java代码如下:

    

[java] view plain copy print ?
  1. public void renameFile (String fromthis, String tothis){  
  2.               Configurationconf = new Configuration();  
  3.                  
  4.               FileSystemfs;  
  5.               try {  
  6.                        fs= FileSystem.get(conf);  
  7.                        PathfromPath = new Path(fromthis);  
  8.                        PathtoPath = new Path(tothis);  
  9.                           
  10.                        if (!(fs.exists(fromPath))) {  
  11.                                 LOG.info("No such destination " + fromPath);  
  12.                            return;  
  13.                        }  
  14.                           
  15.                        if (fs.exists(toPath)) {  
  16.                                 LOG.info("Already exists! " + toPath);  
  17.                            return;  
  18.                        }  
  19.                           
  20.                        try{  
  21.                                 boolean isRenamed = fs.rename(fromPath,toPath);     //renames file name indeed.  
  22.                                 if(isRenamed){  
  23.                                           LOG.info("Renamed from " + fromthis + " to " + tothis);  
  24.                                 }  
  25.                        }catch(Exception e){  
  26.                                 LOG.error("renameFile Exception caught! :" , e);  
  27.                                 new RuntimeException(e);  
  28.                        }finally{  
  29.                                 fs.close();  
  30.                        }  
  31.               }catch (IOException e1) {  
  32.                        LOG.error("fs Exception caught! :" , e1);  
  33.                        new RuntimeException(e1);  
  34.               }  
  35.     }  

 

4 删除

在hdfs上,删除指定的一个文件。Java代码:

[java] view plain copy print ?
  1. public void deleteFile(String file)  {  
  2.                             Configurationconf = new Configuration();  
  3.                             FileSystemfs;  
  4.                             try {  
  5.                                      fs= FileSystem.get(conf);  
  6.           
  7.                                      Pathpath = new Path(file);  
  8.                                      if (!fs.exists(path)) {  
  9.                                                LOG.info("File " + file + " does not exists");  
  10.                                                return;  
  11.                                      }  
  12.                                      /* 
  13.                                       * recursively delete the file(s) if it is adirectory. 
  14.                                       * If you want to mark the path that will bedeleted as 
  15.                                       * a result of closing the FileSystem. 
  16.                                       *  deleteOnExit(Path f) 
  17.                                       */  
  18.                                      fs.delete(new Path(file), true);  
  19.                                      fs.close();  
  20.                             }catch (IOException e) {  
  21.                                      LOG.error("deleteFile Exception caught! :" , e);  
  22.                                      new RuntimeException(e);  
  23.                             }  
  24.    
  25.                    }  


 

Appendix 完整代码

 

[java] view plain copy print ?
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9.    
  10. import org.apache.commons.logging.Log;  
  11. import org.apache.commons.logging.LogFactory;  
  12. import org.apache.hadoop.conf.Configuration;  
  13. import org.apache.hadoop.fs.BlockLocation;  
  14. import org.apache.hadoop.fs.FSDataInputStream;  
  15. import org.apache.hadoop.fs.FSDataOutputStream;  
  16. import org.apache.hadoop.fs.FileStatus;  
  17. import org.apache.hadoop.fs.FileSystem;  
  18. import org.apache.hadoop.fs.LocatedFileStatus;  
  19. import org.apache.hadoop.fs.Path;  
  20. import org.apache.hadoop.fs.RemoteIterator;  
  21. importorg.apache.hadoop.hdfs.DistributedFileSystem;  
  22. import org.apache.hadoop.hdfs.protocol.DatanodeInfo;  
  23.    
  24. public class SyncDFS {  
  25.           
  26.          private static final Log LOG = LogFactory.getLog(SyncDFS.class);  
  27.           
  28.          /** 
  29.           * Reads the directory name(s) and file name(s)from the specified parameter "srcPath" 
  30.           * @param srcPath 
  31.           */  
  32.          public void list(String srcPath) {  
  33.                     Configuration conf = new Configuration();  
  34.                     LOG.info("[Defaultfs] :" +conf.get("fs.default.name"));  
  35. //                conf.set("hadoop.job.ugi","app,app");   //It is not necessary for the default user.  
  36.                     FileSystem fs;  
  37.                    try {  
  38.                             fs= FileSystem.get(conf);  
  39.                             RemoteIterator<LocatedFileStatus>rmIterator = fs.listLocatedStatus(new Path(srcPath));  
  40.                             while (rmIterator.hasNext()) {  
  41.                                       Path path = rmIterator.next().getPath();  
  42.                                       if(fs.isDirectory(path)){  
  43.                                                 LOG.info("-----------DirectoryName: "+path.getName());  
  44.                                       }  
  45.                                       else if(fs.isFile(path)){  
  46.                                                 LOG.info("-----------FileName: "+path.getName());  
  47.                                       }  
  48.                             }  
  49.                    }catch (IOException e) {  
  50.                             LOG.error("list fileSysetm object stream.:" , e);  
  51.                             new RuntimeException(e);  
  52.                    }  
  53.          }  
  54.    
  55.          /** 
  56.           * Makes the specified directory if it doesn'texist. 
  57.           * @param dir 
  58.           */  
  59.          public void mkdir(String dir){  
  60.                    Configurationconf = new Configuration();  
  61.                    FileSystemfs = null;  
  62.                    try {  
  63.                             fs= FileSystem.get(conf);  
  64.                             Pathpath = new Path(dir);  
  65.                             if(!fs.exists(path)){  
  66.                                      fs.mkdirs(path);  
  67.                                      LOG.debug("create directory '"+dir+"' successfully!");  
  68.                             }else{  
  69.                                      LOG.debug("directory '"+dir+"' exits!");  
  70.                             }  
  71.                    }catch (IOException e) {  
  72.                             LOG.error("FileSystem get configuration with anerror");  
  73.                             e.printStackTrace();  
  74.                    }finally{  
  75.                             if(fs!= null){  
  76.                                      try {  
  77.                                                fs.close();  
  78.                                      }catch (IOException e) {  
  79.                                                LOG.error("close fs object stream. :" , e);  
  80.                                                new RuntimeException(e);  
  81.                                      }  
  82.                             }  
  83.                    }  
  84.          }  
  85.           
  86.          /** 
  87.           * Reads the file content in console. 
  88.           * @param file 
  89.           */  
  90.          public void readFile(String file){  
  91.                    Configurationconf = new Configuration();  
  92.                    FileSystemfs;  
  93.                    try {  
  94.                             fs= FileSystem.get(conf);  
  95.                             Pathpath = new Path(file);  
  96.                             if(!fs.exists(path)){  
  97.                                      LOG.warn("file'"+ file+"' doesn't exist!");  
  98.                                      return ;  
  99.                             }  
  100.                             FSDataInputStreamin = fs.open(path);  
  101.                             Stringfilename = file.substring(file.lastIndexOf('/') + 1, file.length());  
  102.                             OutputStreamout = new BufferedOutputStream(new FileOutputStream(  
  103.                                                                             new File(filename)));  
  104.    
  105.                             byte[] b = new byte[1024];  
  106.                             int numBytes = 0;  
  107.                             while ((numBytes = in.read(b)) > 0) {  
  108.                                      out.write(b,0, numBytes);  
  109.                             }  
  110.                             in.close();  
  111.                             out.close();  
  112.                             fs.close();  
  113.                    }catch (IOException e) {  
  114.                             LOG.error("ifExists fs Exception caught! :" , e);  
  115.                             new RuntimeException(e);  
  116.                    }  
  117.          }  
  118.           
  119.          public boolean ifExists(String source){  
  120.                    if(source == null || source.length() ==0){  
  121.                             return false;  
  122.                    }  
  123.                    Configurationconf = new Configuration();  
  124.                    FileSystemfs = null;  
  125.                    try {  
  126.                             fs= FileSystem.get(conf);  
  127.                             LOG.debug("judge file '"+source +  "'");  
  128.                             return fs.exists(new Path(source));  
  129.                    }catch (IOException e) {  
  130.                             LOG.error("ifExists fs Exception caught! :" , e);  
  131.                             new RuntimeException(e);  
  132.                             return false;  
  133.                    }finally{  
  134.                             if(fs != null){  
  135.                                      try {  
  136.                                                fs.close();  
  137.                                      }catch (IOException e) {  
  138.                                                LOG.error("fs.close Exception caught! :" , e);  
  139.                                                new RuntimeException(e);  
  140.                                      }  
  141.                             }  
  142.                              
  143.                    }  
  144.                     
  145.          }  
  146.           
  147.          /** 
  148.           * Recursively copies the source pathdirectories or files to the destination path of DFS. 
  149.           * It is the same functionality as thefollowing comand: 
  150.           *      hadoopfs -copyFromLocal <local fs><hadoop fs> 
  151.           * @param source 
  152.           * @param dest 
  153.           */  
  154.          public void copyFromLocal (String source, String dest) {  
  155.                       
  156.                    Configurationconf = new Configuration();  
  157.                    FileSystemfs;  
  158.                    try {  
  159.                             fs= FileSystem.get(conf);  
  160.                             PathsrcPath = new Path(source);  
  161.                                
  162.                             PathdstPath = new Path(dest);  
  163.                             // Check if the file alreadyexists  
  164.                             if (!(fs.exists(dstPath))) {  
  165.                                      LOG.warn("dstPathpath doesn't exist" );  
  166.                                      LOG.error("No such destination " + dstPath);  
  167.                                      return;  
  168.                             }  
  169.                                
  170.                             // Get the filename out of thefile path  
  171.                             Stringfilename = source.substring(source.lastIndexOf('/') + 1, source.length());  
  172.                                
  173.                             try{  
  174.                                      //if the file exists in thedestination path, it will throw exception.  
  175. //                                   fs.copyFromLocalFile(srcPath,dstPath);  
  176.                                      //remove and overwrite files withthe method  
  177.                                      //copyFromLocalFile(booleandelSrc, boolean overwrite, Path src, Path dst)  
  178.                                      fs.copyFromLocalFile(falsetrue, srcPath, dstPath);  
  179.                                      LOG.info("File " + filename + "copied to " + dest);  
  180.                             }catch(Exception e){  
  181.                                      LOG.error("copyFromLocalFile exception caught!:" , e);  
  182.                                      new RuntimeException(e);  
  183.                             }finally{  
  184.                                      fs.close();  
  185.                             }  
  186.                    }catch (IOException e1) {  
  187.                             LOG.error("copyFromLocal IOException objectstream. :" ,e1);  
  188.                             new RuntimeException(e1);  
  189.                    }  
  190.                    }  
  191.           
  192.           
  193.          public void renameFile (String fromthis, String tothis){  
  194.                    Configurationconf = new Configuration();  
  195.                       
  196.                    FileSystemfs;  
  197.                    try {  
  198.                             fs= FileSystem.get(conf);  
  199.                             PathfromPath = new Path(fromthis);  
  200.                             PathtoPath = new Path(tothis);  
  201.                                
  202.                             if (!(fs.exists(fromPath))) {  
  203.                                      LOG.info("No such destination " + fromPath);  
  204.                                 return;  
  205.                             }  
  206.                                
  207.                             if (fs.exists(toPath)) {  
  208.                                      LOG.info("Already exists! " + toPath);  
  209.                                 return;  
  210.                             }  
  211.                                
  212.                             try{  
  213.                                      boolean isRenamed = fs.rename(fromPath,toPath);     //renames file name indeed.  
  214.                                      if(isRenamed){  
  215.                                                LOG.info("Renamed from " + fromthis + " to " + tothis);  
  216.                                      }  
  217.                             }catch(Exception e){  
  218.                                      LOG.error("renameFile Exception caught! :" , e);  
  219.                                      new RuntimeException(e);  
  220.                             }finally{  
  221.                                      fs.close();  
  222.                             }  
  223.                    }catch (IOException e1) {  
  224.                             LOG.error("fs Exception caught! :" , e1);  
  225.                             new RuntimeException(e1);  
  226.                    }  
  227.          }  
  228.           
  229.          /** 
  230.           * Uploads or adds a file to HDFS 
  231.           * @param source 
  232.           * @param dest 
  233.           */  
  234.          public void addFile(String source, String dest)  {  
  235.                             // Conf object will readthe HDFS configuration parameters  
  236.                             Configurationconf = new Configuration();  
  237.                             FileSystemfs;  
  238.                             try {  
  239.                                      fs= FileSystem.get(conf);  
  240.                                      // Get the filename out of thefile path  
  241.                                      Stringfilename = source.substring(source.lastIndexOf('/') + 1, source.length());  
  242.                                       
  243.                                      // Create the destination pathincluding the filename.  
  244.                                      if (dest.charAt(dest.length() - 1) != '/') {  
  245.                                                dest= dest + "/" + filename;  
  246.                                      }else {  
  247.                                                dest= dest + filename;  
  248.                                      }  
  249.                                       
  250.                                      // Check if the file alreadyexists  
  251.                                      Pathpath = new Path(dest);  
  252.                                      if (fs.exists(path)) {  
  253.                                                LOG.error("File " + dest + " already exists");  
  254.                                                return;  
  255.                                      }  
  256.                                       
  257.                                      // Create a new file and writedata to it.  
  258.                                      FSDataOutputStreamout = fs.create(path);  
  259.                                      InputStreamin = new BufferedInputStream(new FileInputStream(  
  260.                                                                                                                                                      new File(source)));  
  261.                                       
  262.                                      byte[] b = new byte[1024];  
  263.                                      int numBytes = 0;  
  264.                                      //In this way read and write datato destination file.  
  265.                                      while ((numBytes = in.read(b)) > 0) {  
  266.                                                out.write(b,0, numBytes);  
  267.                                      }  
  268.                                      in.close();  
  269.                                      out.close();  
  270.                                      fs.close();  
  271.                             }catch (IOException e) {  
  272.                                      LOG.error("addFile Exception caught! :" , e);  
  273.                                      new RuntimeException(e);  
  274.                             }  
  275.          }  
  276.           
  277.          /** 
  278.           *Deletes the files if it is a directory. 
  279.           * @param file 
  280.           */  
  281.          public void deleteFile(String file)  {  
  282.                             Configurationconf = new Configuration();  
  283.                             FileSystemfs;  
  284.                             try {  
  285.                                      fs= FileSystem.get(conf);  
  286.           
  287.                                      Pathpath = new Path(file);  
  288.                                      if (!fs.exists(path)) {  
  289.                                                LOG.info("File " + file + " does not exists");  
  290.                                                return;  
  291.                                      }  
  292.                                      /* 
  293.                                       * recursively delete the file(s) if it is adirectory. 
  294.                                       * If you want to mark the path that will bedeleted as 
  295.                                       * a result of closing the FileSystem. 
  296.                                       *  deleteOnExit(Path f) 
  297.                                       */  
  298.                                      fs.delete(new Path(file), true);  
  299.                                      fs.close();  
  300.                             }catch (IOException e) {  
  301.                                      LOG.error("deleteFile Exception caught! :" , e);  
  302.                                      new RuntimeException(e);  
  303.                             }  
  304.    
  305.                    }  
  306.          /** 
  307.           * Gets the information about the file modifiedtime. 
  308.           * @param source 
  309.           * @throws IOException 
  310.           */  
  311.          public void getModificationTime(String source) throws IOException{  
  312.                       
  313.                    Configurationconf = new Configuration();  
  314.                       
  315.                    FileSystemfs = FileSystem.get(conf);  
  316.                    PathsrcPath = new Path(source);  
  317.                       
  318.                    // Check if the file alreadyexists  
  319.                    if (!(fs.exists(srcPath))) {  
  320.                    System.out.println("No such destination " + srcPath);  
  321.                    return;  
  322.                    }  
  323.                    // Get the filename out of thefile path  
  324.                    Stringfilename = source.substring(source.lastIndexOf('/') + 1, source.length());  
  325.                       
  326.                    FileStatusfileStatus = fs.getFileStatus(srcPath);  
  327.                    long modificationTime =fileStatus.getModificationTime();  
  328.                       
  329.                    LOG.info("modified datetime: " + System.out.format("File %s; Modification time : %0.2f%n",filename,modificationTime));  
  330.                       
  331.          }  
  332.           
  333.          /** 
  334.           * Gets the file block location info 
  335.           * @param source 
  336.           * @throws IOException 
  337.           */  
  338.          public void getBlockLocations(String source) throws IOException{  
  339.                    Configurationconf = new Configuration();  
  340.                    FileSystemfs = FileSystem.get(conf);  
  341.                    PathsrcPath = new Path(source);  
  342.                       
  343.                    // Check if the file alreadyexists  
  344.                    if (!(ifExists(source))) {  
  345.                             System.out.println("No such destination " + srcPath);  
  346.                             return;  
  347.                    }  
  348.                    // Get the filename out of thefile path  
  349.                    Stringfilename = source.substring(source.lastIndexOf('/') + 1, source.length());  
  350.                       
  351.                    FileStatusfileStatus = fs.getFileStatus(srcPath);  
  352.                       
  353.                    BlockLocation[]blkLocations = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());  
  354.                    int blkCount = blkLocations.length;  
  355.                       
  356.                    System.out.println("File :" + filename + "stored at:");  
  357.                    for (int i=0; i < blkCount; i++) {  
  358.                             String[]hosts = blkLocations[i].getHosts();  
  359.                             LOG.info("host ip:" +System.out.format("Host %d: %s %n", i, hosts));  
  360.                    }  
  361.          }  
  362.           
  363.          public void getHostnames () throws IOException{  
  364.                    Configurationconfig = new Configuration();  
  365.                     
  366.                    FileSystemfs = FileSystem.get(config);  
  367.                    DistributedFileSystemhdfs = (DistributedFileSystem) fs;  
  368.                    DatanodeInfo[]dataNodeStats = hdfs.getDataNodeStats();  
  369.                       
  370.                    String[]names = new String[dataNodeStats.length];  
  371.                    for (int i = 0; i < dataNodeStats.length; i++) {  
  372.                             names[i]= dataNodeStats[i].getHostName();  
  373.                             LOG.info("datenode hostname:"+(dataNodeStats[i].getHostName()));  
  374.                    }  
  375.          }  
  376.          /** 
  377.           * @param args 
  378.           */  
  379.          public static void main(String[] args) {  
  380.                    SyncDFSdfs = new SyncDFS();  
  381.                    dfs.list("/user/app");  
  382.                     
  383.                    dfs.mkdir("/user/app");  
  384.                     
  385. //                dfs.readFile("/user/app/README.txt");  
  386.                    LOG.info("--------------" +  
  387.                              dfs.ifExists("/user/warehouse/hbase.db/u_data/u.data")); //false  
  388.                    LOG.info("--------------" + dfs.ifExists("/user/app/README.txt")); //true  
  389.                     
  390.                    //copied the local file(s) to thedfs.  
  391. //                dfs.copyFromLocal("/opt/test","/user/app");  
  392.                     
  393.                    //delete the file(s) from the dfs  
  394. //                dfs.deleteFile("/user/app/test");  
  395.                    //rename diretory in dfs  
  396. //                dfs.renameFile("/user/app/test","/user/app/log");  
  397.                    //rename file in dfs  
  398. //                dfs.renameFile("/user/app/log/derby.log","/user/app/log/derby_info.log");  
  399.                     
  400.          }  
  401.    
  402.           

你可能感兴趣的:(HDFS CRUD 操作)