京公网安备 11010802034615号
经营许可证编号:京B2-20210330
rm -rf /opt/linuxsir/hadoop/logs/*.*
ssh root@192.168.31.132 rm -rf /opt/linuxsir/hadoop/logs/*.*
ssh root@192.168.31.133 rm -rf /opt/linuxsir/hadoop/logs/*.*
clear
cd /opt/linuxsir/hadoop/sbin
./start-dfs.sh
./start-yarn.sh
clear
jps
ssh root@192.168.31.132 jps
ssh root@192.168.31.133 jps
在eclipse里面操作如下:
New-Java Project,名称自定义即可,如 java-prjNew-Package,名称自定义为com.pai.hdfs_demoNew-Class,名称自定义为ReadWriteHDFSExamplepackage com.pai.hdfs_demo;
import org.apache.commons.io.IOUtils;
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.*;
import java.nio.charset.StandardCharsets;
public class ReadWriteHDFSExample {
// main 新建一个类ReadWriteHDFSExample,编写main函数如下。main函数调用其它函数,创建目录,写入数据,添加数据,然后再读取数据
public static void main(String[] args) throws IOException {
// ReadWriteHDFSExample.checkExists();
ReadWriteHDFSExample.createDirectory();
ReadWriteHDFSExample.writeFileToHDFS();
ReadWriteHDFSExample.appendToHDFSFile();
ReadWriteHDFSExample.readFileFromHDFS();
}
// readFileFromHDFS 该函数读取文件内容,以字符串形式显示出来
public static void readFileFromHDFS() throws IOException {
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS", "hdfs://192.168.31.131:9000");
FileSystem fileSystem = FileSystem.get(configuration);
// Create a path
String fileName = "read_write_hdfs_example.txt";
Path hdfsReadPath = new Path("/javareadwriteexample/" + fileName);
// initialize input stream
FSDataInputStream inputStream = fileSystem.open(hdfsReadPath);
// Classical input stream usage
String out = IOUtils.toString(inputStream, "UTF-8");
System.out.println(out);
// BufferedReader bufferedReader = new BufferedReader(
// new InputStreamReader(inputStream, StandardCharsets.UTF_8));
// String line = null;
// while ((line=bufferedReader.readLine())!=null){
// System.out.println(line);
// }
inputStream.close();
fileSystem.close();
}
// writeFileToHDFS writeFileToHDFS函数打开文件,写入一行文本
public static void writeFileToHDFS() throws IOException {
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS", "hdfs://192.168.31.131:9000");
FileSystem fileSystem = FileSystem.get(configuration);
// Create a path
String fileName = "read_write_hdfs_example.txt";
Path hdfsWritePath = new Path("/javareadwriteexample/" + fileName);
FSDataOutputStream fsDataOutputStream = fileSystem.create(hdfsWritePath, true);
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(fsDataOutputStream, StandardCharsets.UTF_8));
bufferedWriter.write("Java API to write data in HDFS");
bufferedWriter.newLine();
bufferedWriter.close();
fileSystem.close();
}
// appendToHDFSFile 函数打开文件,添加一行文本。需要注意的是,需要对Configuration类的对象configuration进行适当设置,否则出错
public static void appendToHDFSFile() throws IOException {
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS", "hdfs://192.168.31.131:9000");
//configuration.setBoolean("dfs.client.block.write.replace-datanode-on-failure.enabled", true);
configuration.set("dfs.client.block.write.replace-datanode-on-failure.policy","NEVER");
configuration.set("dfs.client.block.write.replace-datanode-on-failure.enable","true");
FileSystem fileSystem = FileSystem.get(configuration);
// Create a path
String fileName = "read_write_hdfs_example.txt";
Path hdfsWritePath = new Path("/javareadwriteexample/" + fileName);
FSDataOutputStream fsDataOutputStream = fileSystem.append(hdfsWritePath);
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(fsDataOutputStream, StandardCharsets.UTF_8));
bufferedWriter.write("Java API to append data in HDFS file");
bufferedWriter.newLine();
bufferedWriter.close();
fileSystem.close();
}
// createDirectory 函数创建一个目录
public static void createDirectory() throws IOException {
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS", "hdfs://192.168.31.131:9000");
FileSystem fileSystem = FileSystem.get(configuration);
String directoryName = "/javareadwriteexample";
Path path = new Path(directoryName);
fileSystem.mkdirs(path);
}
// checkExists checkExists检查目录或者文件是否存在。注意如下代码的最后一个括号是ReadWriteHDFSExample类的结束括号
public static void checkExists() throws IOException {
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS", "hdfs://192.168.31.131:9000");
FileSystem fileSystem = FileSystem.get(configuration);
String directoryName = "/javareadwriteexample";
Path path = new Path(directoryName);
if (fileSystem.exists(path)) {
System.out.println("File/Folder Exists : " + path.getName());
} else {
System.out.println("File/Folder does not Exists : " + path.getName());
}
}
}
为了编译通过上述Java代码,需要把如下目录下的jar包导入Eclipse项目的Build Path
操作序列为 右键点击Eclipse里的Java项目→Properties→Java Build Path →Libraries→Add External Jars
# 添加如下路径的包
D:hadoop-2.7.3sharehadoopcommonlib
D:hadoop-2.7.3sharehadoopcommon
D:hadoop-2.7.3sharehadoophdfs
D:hadoop-2.7.3sharehadoophdfslib
D:hadoop-2.7.3sharehadoopmapreducelib
D:hadoop-2.7.3sharehadoopmapreduce
D:hadoop-2.7.3sharehadoopyarnlib
D:hadoop-2.7.3sharehadoopyarn
就可以愉快地执行了,执行完毕上述代码后,在hd-master主机上可以通过如下命令,检查已经写入的文件
[root@hd-master bin]# cd /opt/linuxsir/hadoop/bin
[root@hd-master bin]# ./hdfs dfs -ls /javareadwriteexample/read_write_hdfs_example.txt
-rw-r--r-- 3 root supergroup 70 2024-10-10 04:47 /javareadwriteexample/read_write_hdfs_example.txt
[root@hd-master bin]# ./hdfs dfs -cat /javareadwriteexample/read_write_hdfs_example.txt
Java API to write data in HDFS
Java API to append data in HDFS file
为了多次进行实验(或者为了调试代码),可以把HDFS文件删除,然后再执行或者调试Java代码,否则一经存在该目录,执行创建目录的代码就会出错
cd /opt/linuxsir/hadoop/bin
./hdfs dfs -rm /javareadwriteexample/*
./hdfs dfs -rmdir /javareadwriteexample
cd /opt/linuxsir/hadoop/sbin
./stop-yarn.sh
./stop-dfs.sh
jps
ssh root@192.168.31.132 jps
ssh root@192.168.31.133 jps
package mywordcount;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class WordCount {
//定义WordCount类的内部类TokenizerMapper 该类实现了map函数,把从文件读取的每个word变成一个形式为<word,1>的Key Value对,输出到map函数的参数context对象,由执行引擎完成Shuffle
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
//定义WordCount类的内部类IntSumReducer 该类实现了reduce函数,它收拢所有相同key的、形式为<word,1>的Key-Value对,对Value部分进行累加,输出一个计数
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
String thekey = key.toString();
int thevalue = sum;
}
}
// WordCount类的main函数,负责配置Job的若干关键的参数,并且启动这个Job。在main函数中,conf对象包含了一个属性即“fs.defaultFS”,它的值为“hdfs://192.168.31.131:9000”,使得WordCount程序知道如何存取HDFS
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
conf.set("fs.defaultFS", "hdfs://192.168.31.131:9000");
Job job = new Job(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
[root@hd-master bin]# ./hdfs dfs -ls /output1
Found 2 items
-rw-r--r-- 3 root supergroup 0 2024-10-10 05:17 /output1/_SUCCESS
-rw-r--r-- 3 root supergroup 89 2024-10-10 05:17 /output1/part-r-00000
[root@hd-master bin]# ./hdfs dfs -cat /output1/part-r-00000
I 1
apache 1
cloudera 1
google 1
hadoop 8
hortonworks 1
ibm 1
intel 1
like 1
microsoft 1
数据分析咨询请扫描二维码
若不方便扫码,搜微信号:CDAshujufenxi
先回答:下半年能考的证书,大致分四类 2026年下半年仍有报名或考试安排的证书,主要集中在四个方向:财会金融类(如注册会计师 ...
2026-10-27毕业后该考什么证书,答案不是一张热门榜单,而是一个顺序问题:先确定你要投的岗位方向,再判断哪些证书现在就能报、哪些要等工 ...
2026-10-2734岁考证,和二十多岁刚毕业时不是同一道题。这个年龄找工作,招聘方通常已经默认你有十年上下的工作积累,会拿“经验能不能直接 ...
2026-10-27咨询岗位最该优先掌握的不是某个工具,而是四类能串起项目全流程的能力:问题定义与结构化拆解、指标与对比分析、数据获取与清洗 ...
2026-10-27多数咨询岗位需要一定程度的数据分析能力,但“需要”不等于“必须会写代码或建模型”。咨询顾问至少要能看懂客户给的数据、把业 ...
2026-10-27咨询岗位的分析能力,不是“会套框架”或“PPT写得漂亮”,而是一条从问题到结论的能力链:问题拆解—假设验证—信息获取—数据 ...
2026-10-27需要,而且它不是“加分项”,是日常工作的基本工具。直播运营每天要面对选品排期、流量承接、转化复盘和投流决策,这些任务的结 ...
2026-10-27证券分析师的培训需求,最好从“最终要交什么”往回推。日常输出大致四类:行业跟踪报告、财报拆解与盈利预测、估值模型、路演与 ...
2026-10-27先给答案:一张四层知识地图 如果只用一句话回答“证券分析师最重要的知识是什么”,答案是:以财务分析和估值建模为硬核,以行 ...
2026-10-27市场策划不是“会写文案、能办活动”这么简单。招聘方真正考察的,是你能否围绕一个业务目标,完成从调研、人群判断、创意主题、 ...
2026-10-27市场运营想靠学习推动职业发展,容易掉进两个坑:一是把课程清单当能力清单,学完不知道用在哪;二是只补营销方法,遇到渠道效果 ...
2026-10-27产品运营做久了,很容易陷入一种忙碌:活动一场接一场,功能推了一版又一版,日报周报天天写,但说不清自己到底积累了什么。想提 ...
2026-10-27运营岗的“快速提升”,不是把Excel、SQL、Python挨个学一遍,而是先补上能立刻改变工作产出的能力。判断标准很直接:同样一场活 ...
2026-10-27优秀市场专员的能力不是单点技能堆出来的,而是“用户洞察—内容与活动策划—渠道获客—数据复盘”四块形成闭环。想快速上手,正 ...
2026-10-27运营专员的“通用知识”,不是一份越长越好的工具清单,而是能支撑日常任务判断的一套底盘。不同细分方向差异很大:用户运营更关 ...
2026-10-27运营专员最常见的困境不是不忙,而是忙完之后说不清效果:活动做了、内容发了、社群拉了人,汇报时却只有“曝光多少、入群多少” ...
2026-10-27运营经理提升职业知识,靠的不是多报几门课,而是先有一张自己的“知识地图”,再按当前岗位最卡壳的环节排顺序。比较实用的做法 ...
2026-10-27运营岗位的能力素质提升,核心不是把工具学一遍,而是围绕“目标拆解—用户洞察—执行落地—数据复盘”四层能力逐层补齐。工具是 ...
2026-10-27运营岗位的能力提升,最容易走成两条弯路:一是把“提升”等同于学工具,Excel、SQL、Python挨个报班,回到工作里还是凭经验拍脑 ...
2026-10-27运营岗最容易陷入的学习误区,是把“提升”等同于收藏平台玩法、追热点模板、背活动话术。这些内容有用,但迁移性差:换个行业、 ...
2026-10-27