21xrx.com
2025-04-21 14:18:50 Monday
文章检索 我的文章 写文章
我最近在学习Java
2023-06-16 12:05:38 深夜i     11     0
Java HDFS 读取文件

我最近在学习Java,其中一个任务是读取HDFS文件。经过一番探索和测试,我总结了一些有用的代码,分享给大家。以下是这个过程中用到的三个

首先,我们需要在Java程序中引入hadoop的依赖,这样才能访问HDFS。具体地,我们需要在pom.xml文件中添加以下代码:

org.apache.hadoop
 
  
  hadoop-client
 
  
  2.7.3

接下来,我们可以使用以下Java代码打开一个HDFS文件并读取其中的内容:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSReadFile {
 public static void main(String[] args) throws Exception {
  String uri = "hdfs://localhost:8020/path/to/file";
  Configuration conf = new Configuration();
  FileSystem fs = FileSystem.get(URI.create(uri), conf);
  Path path = new Path(uri);
  BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path)));
  String line;
  while ((line = br.readLine()) != null) {
   System.out.println(line);
  }
  br.close();
  fs.close();
 }
}

在这个例子中,我们使用了BufferedReader来逐行读取文件内容,然后将其输出到控制台。需要注意的是,这里的uri应该是文件在HDFS中的完整路径,而不是本地路径。

除了逐行读取,我们还可以使用以下代码读取整个文件并将其以字符串形式返回:

import java.io.InputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public class HDFSReadFileAsString {
 public static String readHDFSFileAsString(String uri) throws Exception {
  Configuration conf = new Configuration();
  FileSystem fs = FileSystem.get(URI.create(uri), conf);
  Path path = new Path(uri);
  InputStream in = fs.open(path);
  byte[] buffer = new byte[4096];
  StringBuilder sb = new StringBuilder();
  int bytesRead = 0;
  while ((bytesRead = in.read(buffer)) > 0) {
   sb.append(new String(buffer, 0, bytesRead));
  }
  in.close();
  fs.close();
  return sb.toString();
 }
}

以上就是我在学习Java读取HDFS文件时总结的一些有用的代码。如果你也需要实现这个功能,可以尝试使用其中的代码。

  
  

评论区