Flink从入门到实战四[DataStream API]-6-Source-从文件中读取数据

Flink 从文件中获取数据

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * Stream Source From Collection
 */
public class StreamSourceFromCollection {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
		
	//从文件中获取数据
        String input = "D:\\______flink______\\input\\wordcount.txt";
        DataStream<String> dataStreamSource = env.readTextFile(input);

        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = dataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = s.split(" ");
                Arrays.stream(words).forEach((String sp) -> collector.collect(new Tuple2<String, Integer>(sp, 1)));
            }
        }).keyBy(item -> item.f0)
                .sum(1);

        sum.print();
        env.execute();
    }
}

输出结果:

5> (hello,1)
9> (fine,1)
5> (hello,2)
16> (Flink,1)
6> (thank,1)
13> (Java,1)
8> (are,1)
3> (I'm,1)
15> (and,1)
11> (how,1)
10> (you,1)
10> (you,2)
10> (you,3)
3> (I'm,2)
1> (Ok,1)