hdfs 文件操作

  1. import java.io.ByteArrayInputStream;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.OutputStream;  
  5. import java.net.URI;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import org.apache.commons.lang.StringUtils;  
  10. import org.apache.hadoop.conf.Configuration;  
  11. import org.apache.hadoop.fs.FSDataInputStream;  
  12. import org.apache.hadoop.fs.FSDataOutputStream;  
  13. import org.apache.hadoop.fs.FileStatus;  
  14. import org.apache.hadoop.fs.FileSystem;  
  15. import org.apache.hadoop.fs.Path;  
  16. import org.apache.zookeeper.common.IOUtils;  
  17.   
  18. /** 
  19.  * operate hdfs file or directory util class 
  20.  *  
  21.  * @author zhang 
  22.  * @since 2016-09-26 
  23.  * 
  24.  */  
  25. public class HdfsUtils {  
  26.   
  27.     public static String uri = "hdfs://192.168.1.118:9000";  
  28.   
  29.     /** 
  30.      * 创建文件夹
  31.      *  
  32.      * @param dir 文件夹路径 '/tmp/testdir' 
  33.      * @return boolean true-success, false-failed 
  34.      * @exception IOException something wrong happends when operating files 
  35.      */  
  36.     public static boolean mkdir(String dir) throws IOException {  
  37.         if (StringUtils.isBlank(dir)) {  
  38.             return false;  
  39.         }  
  40.         dir = uri + dir;  
  41.         Configuration conf = new Configuration();  
  42.         FileSystem fs = FileSystem.get(URI.create(dir), conf);  
  43.         if (!fs.exists(new Path(dir))) {  
  44.             fs.mkdirs(new Path(dir));  
  45.         }  
  46.   
  47.         fs.close();  
  48.         return true;  
  49.     }  
  50.   
  51.     /** 
  52.      * 删除文件夹 
  53.      * if dir not exists, it will throw FileNotFoundException 
  54.      *  
  55.      * @param dir要删除文件夹路径 '/tmp/testdir' 
  56.      * @return boolean true-success, false-failed 
  57.      * @exception IOException something wrong happends when operating files 
  58.      *  
  59.      */  
  60.     public static boolean deleteDir(String dir) throws IOException {  
  61.         if (StringUtils.isBlank(dir)) {  
  62.             return false;  
  63.         }  
  64.         dir = uri + dir;  
  65.         Configuration conf = new Configuration();  
  66.         FileSystem fs = FileSystem.get(URI.create(dir), conf);  
  67.         fs.delete(new Path(dir), true);  
  68.         fs.close();  
  69.         return true;  
  70.     }  
  71.   
  72.     /** 
  73.      * 获取hdfs中指定文件夹下所有文件信息
  74.      *  
  75.      * @param dir a folder path may like '/tmp/testdir' 
  76.      * @return List<String> list of file names 
  77.      * @throws IOException file io exception 
  78.      */  
  79.     public static List<String> listAll(String dir) throws IOException {  
  80.         if (StringUtils.isBlank(dir)) {  
  81.             return new ArrayList<String>();  
  82.         }  
  83.         dir = uri + dir;  
  84.         Configuration conf = new Configuration();  
  85.         FileSystem fs = FileSystem.get(URI.create(dir), conf);  
  86.         FileStatus[] stats = fs.listStatus(new Path(dir));  
  87.         List<String> names = new ArrayList<String>();  
  88.         for (int i = 0; i < stats.length; ++i) {  
  89.             if (stats[i].isFile()) {  
  90.                 // regular file  
  91.                 names.add(stats[i].getPath().toString());  
  92.             } else if (stats[i].isDirectory()) {  
  93.                 // dir  
  94.                 names.add(stats[i].getPath().toString());  
  95.             } else if (stats[i].isSymlink()) {  
  96.                 // is s symlink in linux  
  97.                 names.add(stats[i].getPath().toString());  
  98.             }  
  99.         }  
  100.   
  101.         fs.close();  
  102.         return names;  
  103.     }  
  104.   
  105.     /* 
  106.      * 上传文件到hdfs,  
  107.      * notice that the path is full like /tmp/test.txt 
  108.      * if local file not exists, it will throw a FileNotFoundException 
  109.      *  
  110.      * @param localFile local file path, may like F:/test.txt or /usr/local/test.txt 
  111.      *  
  112.      * @param hdfsFile hdfs file path, may like /tmp/dir 
  113.      * @return boolean true-success, false-failed 
  114.      *  
  115.      * @throws IOException file io exception 
  116.      */  
  117.     public static boolean uploadLocalFile2HDFS(String localFile, String hdfsFile) throws IOException {  
  118.         if (StringUtils.isBlank(localFile) || StringUtils.isBlank(hdfsFile)) {  
  119.             return false;  
  120.         }  
  121.         hdfsFile = uri + hdfsFile;  
  122.         Configuration config = new Configuration();  
  123.         FileSystem hdfs = FileSystem.get(URI.create(uri), config); 
  124.  
  125.         // FSDataOutputStream create = fs.create(new Path(hdfsFile+"/"+文件名)); 获取文件输出流
  126. //             获取文件输出流2
  127. //         OutputStream out = fs.create(new Path(DEST_PATH), new Progressable() {  
    //             @Override  
    //             public void progress() {  
    //                 System.out.println("上传完一个设定缓存区大小容量的文件!");  
    //             }  
    //         }); 
  128.         /*byte[] buffer = new byte[1024];  
            int len = 0;  
            while((len=in.read(buffer))>0){  
                out.write(buffer, 0, len);  
            }   
            out.flush();  
            in.close();  
            out.close();
  129.         */
  130.         Path src = new Path(localFile);  
  131.         Path dst = new Path(hdfsFile);  
  132.         hdfs.copyFromLocalFile(src, dst);  
  133.         hdfs.close();  
  134.         return true;  
  135.     }  
  136.   
  137.     /* 
  138.      * 在hdfs中新建文件. 
  139.      *  
  140.      * notice that the toCreateFilePath is the full path 
  141.      *  
  142.      * and write the content to the hdfs file. 
  143.      */  
  144.     /** 
  145.      * create a new file in the hdfs. 
  146.      * if dir not exists, it will create one 
  147.      *  
  148.      * @param newFile new file path, a full path name, may like '/tmp/test.txt' 
  149.      * @param content file content 
  150.      * @return boolean true-success, false-failed 
  151.      * @throws IOException file io exception 
  152.      */  
  153.     public static boolean createNewHDFSFile(String newFile, String content) throws IOException {  
  154.         if (StringUtils.isBlank(newFile) || null == content) {  
  155.             return false;  
  156.         }  
  157.         newFile = uri + newFile;  
  158.         Configuration config = new Configuration();  
  159.         FileSystem hdfs = FileSystem.get(URI.create(newFile), config);  
  160.         FSDataOutputStream os = hdfs.create(new Path(newFile));  
  161.         os.write(content.getBytes("UTF-8"));  
  162.         os.close();  
  163.         hdfs.close();  
  164.         return true;  
  165.     }  
  166.   
  167.     /** 
  168.      * 删除hdfs中文件 
  169.      *  
  170.      * @param hdfsFile a full path name, may like '/tmp/test.txt' 
  171.      * @return boolean true-success, false-failed 
  172.      * @throws IOException file io exception 
  173.      */  
  174.     public static boolean deleteHDFSFile(String hdfsFile) throws IOException {  
  175.         if (StringUtils.isBlank(hdfsFile)) {  
  176.             return false;  
  177.         }  
  178.         hdfsFile = uri + hdfsFile;  
  179.         Configuration config = new Configuration();  
  180.         FileSystem hdfs = FileSystem.get(URI.create(hdfsFile), config);  
  181.         Path path = new Path(hdfsFile);  
  182.         boolean isDeleted = hdfs.delete(path, true);  
  183.         hdfs.close();  
  184.         return isDeleted;  
  185.     }  
  186.   
  187.     /** 
  188.      * 获取hdfs中指定文件内容 
  189.      *  
  190.      * @param hdfsFile a full path name, may like '/tmp/test.txt' 
  191.      * @return byte[] file content 
  192.      * @throws IOException file io exception 
  193.      */  
  194.     public static byte[] readHDFSFile(String hdfsFile) throws Exception {  
  195.         if (StringUtils.isBlank(hdfsFile)) {  
  196.             return null;  
  197.         }  
  198.         hdfsFile = uri + hdfsFile;  
  199.         Configuration conf = new Configuration();  
  200.         FileSystem fs = FileSystem.get(URI.create(hdfsFile), conf);  
  201.         // check if the file exists  
  202.         Path path = new Path(hdfsFile);  
  203.         if (fs.exists(path)) {  
  204.             FSDataInputStream is = fs.open(path);  
  205.             // get the file info to create the buffer  
  206.             FileStatus stat = fs.getFileStatus(path);  
  207.             // create the buffer  
  208.             byte[] buffer = new byte[Integer.parseInt(String.valueOf(stat.getLen()))];  
  209.             is.readFully(0, buffer);  
  210.             is.close();  
  211.             fs.close();  
  212.             return buffer;  
  213.         } else {  
  214.             throw new Exception("the file is not found .");  
  215.         }  
  216.     }  
  217.   
  218.     /** 
  219.      * 在hdfs中指定文件中追加内容 
  220.      *  
  221.      * @param hdfsFile a full path name, may like '/tmp/test.txt' 
  222.      * @param content string 
  223.      * @return boolean true-success, false-failed 
  224.      * @throws Exception something wrong 
  225.      */  
  226.     public static boolean append(String hdfsFile, String content) throws Exception {  
  227.         if (StringUtils.isBlank(hdfsFile)) {  
  228.             return false;  
  229.         }  
  230.         if(StringUtils.isEmpty(content)){  
  231.             return true;  
  232.         }  
  233.   
  234.         hdfsFile = uri + hdfsFile;  
  235.         Configuration conf = new Configuration();  
  236.         // solve the problem when appending at single datanode hadoop env    
  237.         conf.set("dfs.client.block.write.replace-datanode-on-failure.policy""NEVER");  
  238.         conf.set("dfs.client.block.write.replace-datanode-on-failure.enable""true");  
  239.         FileSystem fs = FileSystem.get(URI.create(hdfsFile), conf);  
  240.         // check if the file exists  
  241.         Path path = new Path(hdfsFile);  
  242.         if (fs.exists(path)) {  
  243.             try {  
  244.                 InputStream in = new ByteArrayInputStream(content.getBytes());  
  245.                 OutputStream out = fs.append(new Path(hdfsFile));  
  246.                 IOUtils.copyBytes(in, out, 4096true);  
  247.                 out.close();  
  248.                 in.close();  
  249.                 fs.close();  
  250.             } catch (Exception ex) {  
  251.                 fs.close();  
  252.                 throw ex;  
  253.             }  
  254.         } else {  
  255.             HdfsUtils.createNewHDFSFile(hdfsFile, content);  
  256.         }  
  257.         return true;  
  258.     }  
  259.   
  260. }  


猜你喜欢

转载自blog.csdn.net/qq_38621910/article/details/80401552