hdfs上单机版词频分析小案例

需求:

统计hdfs上某个文件中词频个数,并将统计结果存储到hdfs上的另一个文件中

需求分析:

连接hdfs,从hsfs上读取文件,按行读取;
将读取到的数据按空格切割字符串,分割单词;
遍历分割后的字符串数组,使用map函数去重,统计词频个数;
遍历map中数据,循环将每一条数据写入hdfs上的某个文件中;
在hsfs上使用 hadoop fs -ls 目录/文件名查看是否写入成功。

代码部分:

public class WordCount{
    public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException {
    HashMap<String, Integer> map = new HashMap<>();
    //连接hdfs
    FileSystem.getFileSystem fs = FileSystem.get(new URI("hdfs://hadoop01:9000"), new Configuration(), "root");
    //使用流数据读取hdfs上的文件
    FSDataInputStream inputStream = fs.open(new Path("/ghm.txt"));
    //为了实现按行读取,使用缓冲流读取文件
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        //循环读取每一行文件
        while((line=reader.readLine())!=null) {
        根据空格或tab分割字符串,分割出每个单词
            String[] split = line.split("\\s");
            //循环遍单词数组使用map函数去重并统计词频个数
            for (String word : split) {
                Integer count = map.getOrDefault(word, 0);
                count++;
                map.put(word, count);
            }   
        }
        //指定文件要写入的位置
        FSDataOutputStream create = fs.create(new Path("/part-r-0001"));
        //循环遍历map中数据,将map中数据写入hdfs
        Set<Entry<String, Integer>> entrySet = map.entrySet();
        for (Entry<String, Integer> entry : entrySet) {
        //执行写入操作    create.write((entry.getKey()+"="+entry.getValue()+"\r\n").getBytes());
            System.out.println(entry);
        }
        //关闭资源
        create.close();
        reader.close();
        inputStream.close();
        fs.close();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值