如何用java下载hdfs文件到本地

1603
2024/3/29 14:28:00
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

你可以使用Hadoop的FileSystem API来下载HDFS文件到本地。以下是一个简单的Java程序示例:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DownloadHdfsFile {

    public static void main(String[] args) {
        String hdfsFilePath = "/path/to/hdfs/file";
        String localFilePath = "/path/to/local/file";

        Configuration conf = new Configuration();
        try {
            FileSystem fs = FileSystem.get(conf);
            Path hdfsPath = new Path(hdfsFilePath);
            InputStream inputStream = fs.open(hdfsPath);
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFilePath));

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, bytesRead);
            }

            inputStream.close();
            outputStream.close();
            fs.close();

            System.out.println("File downloaded successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,你需要将hdfsFilePathlocalFilePath替换为实际的HDFS文件路径和本地文件路径。然后运行程序,即可将HDFS文件下载到本地。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java如何修改list中对象的值