将二进制文件上传到HDFS主要有以下三种方法,可根据具体需求选择合适的方式:
一、使用Hadoop命令行工具(推荐)
通过`hadoop fs -put`命令直接上传,操作简单且适用于小到中等规模文件。例如:
```bash
hadoop fs -put /本地路径/文件 hdfs://namenode:port/user/hdfs路径/
```
此方法无需编写代码,适合快速、批量上传。
二、使用Java API编程上传
通过Hadoop API实现更灵活的文件操作,适用于需要自动化或集成到程序中的场景。示例代码如下:
```java
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.FileInputStream;
import java.io.OutputStream;
public class UploadFile {
public static void main(String[] args) throws Exception {
String localFilePath = "/本地路径/文件";
String hdfsDirectoryPath = "hdfs://namenode:port/user/hdfs路径/";
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI(hdfsDirectoryPath), conf);
Path targetPath = new Path(hdfsDirectoryPath + localFilePath.substring(localFilePath.lastIndexOf('/') + 1));
try (FileInputStream fis = new FileInputStream(localFilePath);
OutputStream os = fs.create(targetPath)) {
byte[] buffer = new byte;
int bytesRead;
while ((bytesRead = fis.read(buffer)) > 0) {
os.write(buffer, 0, bytesRead);
}
}
fs.close();
}
}
```
此方法支持分块上传,适合大文件处理。
三、使用Hadoop API的Writer对象(压缩场景)
若需压缩文件,可通过`FileSystem.create`方法创建`Writer`对象,例如:
```java
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
Path outputPath = new Path("hdfs://namenode:port/user/hdfs路径/压缩文件名.gz");
try (OutputStream os = fs.create(outputPath, true)) { // 第二个参数为true表示启用压缩
// 写入数据
}
```
此方法适用于需要压缩存储的场景。
注意事项:
1. 上传前需确保HDFS服务正常运行,并创建目标目录(如`hdfs://localhost:9000/user/hdfs路径/`)。
2. 大文件建议使用分块上传或Java API,避免Driver内存溢出。
3. 压缩文件时需注意压缩算法与HDFS支持的格式兼容性。