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

19次阅读
没有评论

共计 1046 个字符,预计需要花费 3 分钟才能阅读完成。

你可以使用 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 文件下载到本地。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-04-07发表,共计1046字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)