12.5每日总结3

发布时间 2023-12-05 23:19:39作者: 听着DJ读童话

将HDFS中指定文件的内容输出到终端中;

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

import java.io.*;

public class Cat {
/**
* 读取文件内容
*/
public static void cat(Configuration conf, String remoteFilePath) {
Path remotePath = new Path(remoteFilePath);
try (FileSystem fs = FileSystem.get(conf);
FSDataInputStream in = fs.open(remotePath);
BufferedReader d = new BufferedReader(new InputStreamReader(in));) {
String line;
while ((line = d.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 主函数
*/
public static void main(String[] args) {
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://localhost:9000");
String remoteFilePath = "/user/tiny/input/text.txt"; // HDFS路径

try {
System.out.println("读取文件: " + remoteFilePath);
Cat.cat(conf, remoteFilePath);
System.out.println("\n读取完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}