21xrx.com
2025-04-06 15:59:37 Sunday
文章检索 我的文章 写文章
Hadoop分布式文件系统HDFS是一个高度可扩展的分布式文件系统
2023-06-15 11:41:56 深夜i     6     0

我了解到,Hadoop分布式文件系统HDFS是一个高度可扩展的分布式文件系统,它是Hadoop的一个子项目。在我的项目中,我需要使用java api访问HDFS。下面是我的代码例子:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
public class HDFSExample {
public void readFileFromHDFS(String filename) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(filename), conf);
Path path = new Path(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path)));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
public void writeFileToHDFS(String filename, String content) throws Exception {
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(filename), conf);
Path path = new Path(filename);
fs.delete(path, true);
fs.create(path);
fs.setReplication(path, (short) 1);
fs.setWritable(path, true);
fs.setReadable(path, true);
fs.setPermission(path, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.READ_EXECUTE));
OutputStream out = fs.append(path);
out.write(content.getBytes());
out.flush();
out.close();
}
public static void main(String[] args) throws Exception {
String filename = "hdfs://localhost:9000/user/hadoop/test.txt";
HDFSExample example = new HDFSExample();
example.readFileFromHDFS(filename);
example.writeFileToHDFS(filename, "Hello Hadoop!\n");
}
}

在这个例子中,我使用了java api对一个HDFS的文件进行了读写操作。在运行之前,你需要先确保Hadoop已经安装好,并且在core-site.xml和hdfs-site.xml中配置好了HDFS的相关信息。关键词包括:java api、HDFS、Hadoop。我的标题为“使用Java API进行HDFS读写操作”。

  
  

评论区

请求出错了