使用hdfs的api在hdfs上编程完成以下操作(包括import语句) 在根目录创建/hdfstest目录 上传本地(windows系统)D盘根目录下的“hij.txt”到“/pytest”目录下 向“/hdfstest/hij.txt”中写入“hello world”内容 使用read读出文件的内容 打印输出文件的内容
时间: 2024-03-17 12:44:07 浏览: 22
好的,以下是使用hdfs的api在hdfs上编程完成以上操作的代码(Java语言):
```
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class HdfsTest {
public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
// 创建HDFS文件系统对象
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://localhost:9000"), conf, "root");
// 在根目录创建/hdfstest目录
Path dirPath = new Path("/hdfstest");
fs.mkdirs(dirPath);
// 上传本地(windows系统)D盘根目录下的“hij.txt”到“/pytest”目录下
Path localFilePath = new Path("D:/hij.txt");
Path hdfsFilePath = new Path("/hdfstest/hij.txt");
fs.copyFromLocalFile(localFilePath, hdfsFilePath);
// 向“/hdfstest/hij.txt”中写入“hello world”内容
FSDataOutputStream out = fs.append(hdfsFilePath);
out.writeUTF("hello world");
out.hsync();
out.close();
// 使用read读出文件的内容
FSDataInputStream in = fs.open(hdfsFilePath);
byte[] buffer = new byte[1024];
int bytesRead = in.read(buffer);
String content = new String(buffer, 0, bytesRead);
// 打印输出文件的内容
System.out.println(content);
// 关闭文件系统对象
fs.close();
}
}
```
需要注意的是,以上代码中的HDFS连接地址、用户名等信息需要根据实际情况进行修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)