参考:Hadoop 3.x HDFS 写入文件 中 客户端环境变量配置
三、在客户端节点上 上传实例文件1、编辑文件 WangYue.txt
[root@slave1 ~]# vim ~/WangYue.txt
2、写入内容:
望岳
岱宗夫如何?齐鲁青未了。
造化钟神秀,阴阳割昏晓。
荡胸生曾云,决眦入归鸟。
会当凌绝顶,一览众山小。
3、把 文件 WangYue.txt 上传至 hdfs
[root@slave1 ~]# hdfs dfs -put ./WangYue.txt /
4、查看 hdfs 目录
[root@slave1 ~]# hdfs dfs -ls /
5、查看 hdfs 中文件内容
[root@slave1 ~]# hdfs dfs -cat /WangYue.txt
1、编辑文件
[root@slave1 ~]# vim ~/ReadFile.java
2、写入内容
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public class ReadFile {
public static void main(String[] args) {
Configuration conf = new Configuration();
Path inFile = new Path("/WangYue.txt");
FileSystem hdfs ;
FSDataInputStream inputStream = null;
try {
hdfs = FileSystem.get(conf);
inputStream = hdfs.open(inFile);
IOUtils.copyBytes(inputStream, System.out, 1024,false);
} catch (IOException e) {
e.printStackTrace();
}finally {
IOUtils.closeStream(inputStream);
}
}
}
3、编译
[root@slave1 ~]# javac ~/ReadFile.java
4、打包
[root@slave1 ~]# jar -cvf ReadFile.jar ReadFile.class
1、在客户端节点上使用 hadoop jar 命令执行 ReadFile.jar
[root@slave1 ~]# hadoop jar ~/ReadFile.jar ReadFile
2、效果如下:
Hadoop 读取文件 报错 java.io.EOFException 时 需要使用 IOUtils 工具
FSDataInputStream对象 读取数据原理
至此 Centos7.x Hadoop 3.x HDFS 读取文件操作完毕,希望能够对您有所帮助!