針對 Hadoop 分散式檔案系統 (HDFS) 的常見檔案操作,本文提供一個封裝良好的 Java 工具類 HadoopFile,涵蓋從本地上傳至 HDFS、從 HDFS 下載到本地、以及刪除 HDFS 檔案三大核心功能,適合快速整合至大數據應用專案中。
HadoopFile 類別接受 Configuration 物件初始化,預設載入 core-site.xml。三個主要公共方法分別對應上傳、刪除、下載,皆回傳 boolean 表示成敗。
LocalFileSystem 與 DistributedFileSystem 實例。Path,使用 FSDataOutputStream 寫入。FileSystem.delete(Path, true) 遞歸刪除,支援目錄與檔案。FSDataInputStream,寫入本地 FSDataOutputStream。try {
FileSystem localFS = FileSystem.getLocal(conf);
FileSystem hadoopFS = FileSystem.get(conf);
Path hadPath = new Path(hdfsPath);
FSDataOutputStream fsOut = hadoopFS.create(new Path(hdfsPath + "/" + file.getName()));
FSDataInputStream fsIn = localFS.open(new Path(localFile));
byte[] buf = new byte[1024];
int readBytes;
while ((readBytes = fsIn.read(buf)) > 0) {
fsOut.write(buf, 0, readBytes);
}
fsIn.close();
fsOut.close();
// 列出目錄確認
FileStatus[] files = hadoopFS.listStatus(hadPath);
for (FileStatus fs : files) System.out.println(fs);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Configuration 交由 Spring 或依賴注入框架管理。