HDFS的javaAPI使用

工作中做資源服務器時用到了HDFS作爲資源底層存儲,記錄一下使用的API

public class HdfsUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(HdfsUtil.class);

    private HdfsUtil() {
    }
    
    private static FileSystem initFileSystem() {
        Configuration configuration = new Configuration();
        configuration.set("fs.defaultFS", "hdfs:///CDH-01:9990");
        // 這個解決hdfs問題
        configuration.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
        // 這個解決本地file問題
        configuration.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName());
        FileSystem fileSystem = null;
        try {
            fileSystem = FileSystem.get(configuration);
        } catch (Exception e) {
            logger.error("init HDFS system exception!", e);
        }
        return fileSystem;
    }
    
    public static void uploadFile(String src, String dst) throws IOException {
        FileSystem fileSystem = initFileSystem();
        fileSystem.mkdirs(new Path(dst));
        fileSystem.moveFromLocalFile(new Path(src), new Path(dst));
        fileSystem.close();
    }
    
    public static void downloadFile(String src, String dst) throws IOException {
        FileSystem fileSystem = initFileSystem();
        // fileSystem.copyToLocalFile(new Path(src), new Path(dst));
        try (InputStream is = fileSystem.open(new Path(src))) {
            IOUtils.copyBytes(is, new FileOutputStream(new File(dst)), 2048, true);
        }
        fileSystem.close();
    }
    
    public static boolean deleteFile(String filePath) throws IOException {
        // recursive:true 即默認使用遞歸刪除
        return initFileSystem().delete(new Path(filePath), true);
    }
    
    private static boolean makeDir(String dirs) throws IOException {
        return initFileSystem().mkdirs(new Path(dirs));
    }
    
    public static boolean renameDir(String src, String dst) throws IOException {
        return initFileSystem().rename(new Path(src), new Path(dst));
    }
}

使用的依賴包如下:

<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-hdfs</artifactId>
    <version>2.6.0</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-common</artifactId>
    <version>2.6.0</version>
</dependency>

有幾點需要注意:

  • 建議把HADOOP的core-site.xml文件放到代碼工程中的resources目錄中,這樣Configuration類在初始化的時候會默認讀取該文件中的配置,如fs.defaultFS參數
  • FileSystem每次使用完都需要關閉,下次使用時仍需要初始化一個新的
  • downloadFile()方法中的copyToLocalFile()方法嘗試後發現不可行,後採用了註釋下方的代碼解決了問題
  • 如果只是用到了HDFS的客戶端,不建議引用hadoop完整的依賴包(hadoop-client),實在太大了,只需要按照我上面的引入其中兩個依賴包即可
  • hadoop客戶端依賴版本最好和服務端保持一致,否則容易出現兼容性問題
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章