案例需求:统计一个文件中的单词出现的总次数,并且把结果存储到文件中。
Java代码实现如下。
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.util.Collector;
/**
* Batch离线批处理
* 单词计数之离线计算,指定位置读取文件统计单词后输出文件
* @author yishuiping
* @date 2020/12/3 15:30
*/
public class BatchWordCountJava {
public static void main(String[] args) throws Exception {
String inputPath = "D:\\data\\file";
String outPath = "D:\\data\\result";
//获取运行环境
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
//获取文件中的内容
DataSource<String> text = env.readTextFile(inputPath);
//筛选计算单词的数量
DataSet<Tuple2<String, Integer>> counts = text.flatMap(new Tokenizer()).groupBy(0).sum(1);
//统计结果写到指定的输出目录中,如果有该文件就覆盖掉。
counts.writeAsCsv(outPath, "\n", " ", FileSystem.WriteMode.OVERWRITE).setParallelism(1);
//调用execute()触发执行程序
env.execute("batch word count");
}
public static class Tokenizer implements FlatMapFunction<String, Tuple2<String,
Integer>> {
public void flatMap(String value, Collector<Tuple2<String, Integer>> out)
throws Exception {
String[] tokens = value.toLowerCase().split("\\W+");
for (String token : tokens) {
if (token.length() > 0) {
out.collect(new Tuple2<String, Integer>(token, 1));
}
}
}
}
}
源文件如图:
要统计的文件.png
结果文件如图:
结果文件.png
网友评论