开头批注:这个教程很多地方已经有一模一样的代码了,只是放在这里当个记录留个纪念吧,都是验证过的代码
目标:输入美国气象局以前的天气记录(ftp://ftp.ncdc.noaa.gov/pub/data/noaa/),获得这一年/每年最低气温
cd /usr/local/hadoop/
mkdir temperature
cd temperature
wget http://labfile.oss.aliyuncs.com/courses/237/temperature.zip
unzip temperature.zip
cd 1971
zcat *.gz > /usr/local/hadoop/temperature.txt
cd ../../
hadoop fs -mkdir -p /class5/in
hadoop fs -copyFromLocal temperature.txt /class5/in
hadoop fs -ls /class5/in
MinTemperature.java
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Job;
public class MinTemperature{
public static void main(String[] args) throws Exception {
if (args.length !=2) {
System.err.println("Usage: MinTemperature
MinTemperatureMapper.java
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class MinTemperatureMapper extends Mapper{
private static final int MISSING = 9999;
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{
String line = value.toString();
String year = line.substring(15, 19);
int airTemperature;
if (line.charAt(87) == '+') {
airTemperature = Integer.parseInt(line.substring(88 , 92));
} else {
airTemperature = Integer.parseInt(line.substring(87 , 92));
}
//airTemperature = Integer.parseInt(line.substring(14, 19).trim());
String quality = line.substring(92, 93);
if (airTemperature != MISSING && quality.matches("[01459]")) {
context.write(new Text(year), new IntWritable(airTemperature));
}
//if(airTemperature!= MISSING){
// context.write(new Text(year), new IntWritable(airTemperature));
//}
}
}
MinTemperatureReducer.java
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class MinTemperatureReducer
extends Reducer
{
@Override
public void reduce(Text key, Iterable values,Context context)
throws IOException, InterruptedException
{
int minValue= Integer.MAX_VALUE;
for (IntWritable value : values)
{
minValue= Math.min(minValue, value.get());
}
context.write(key, new IntWritable(minValue));
}
}
javac MinTemperatur*.java
jar cvf ./MinTemperature.jar ./Min*.class
mv MinTemperature.jar ..
hadoop fs -rm -r -skipTrash /class5/out
(注,上一句是先把上次的输出文件夹删了,否则bug,没有文件夹就不写)
cd ../
hadoop jar MinTemperature.jar MinTemperature /class5/in/temperature.txt /class5/out
cd /usr/local/hadoop
hadoop jar MinTemperature.jar MinTemperature /class5/in/temperature.txt /class5/out
hadoop fs -ls /class5/out
hadoop fs -cat /class5/out/part-r-00000