首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Hadoop Map Reduce读取文本文件

Hadoop Map Reduce读取文本文件
EN

Stack Overflow用户
提问于 2014-10-06 11:45:30
回答 1查看 32.9K关注 0票数 12

我正在尝试编写一个MapReduce程序,它可以读取输入文件并将输出写入另一个文本文件。为此,我计划使用BufferedReader类。但我真的不知道如何在MapReduce程序中使用它。

有人能给我它的代码片段吗?

附言:我对Hadoop和MapReduce编程完全陌生。所以请耐心听我说。

提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-06 13:07:40

下面的代码帮助您从HDFS读取文件并在控制台中显示内容

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class Cat{
    public static void main (String [] args) throws Exception{
        try{
            Path pt=new Path("hdfs:/path/to/file");//Location of file in HDFS
            FileSystem fs = FileSystem.get(new Configuration());
            BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(pt)));
            String line;
            line=br.readLine();
            while (line != null){
                System.out.println(line);
                line=br.readLine();
            }
        }catch(Exception e){
        }
    }
}

编辑

司机

代码语言:javascript
复制
public class ReadFile {

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = new Job(conf, "Read a File");


        FileSystem fs = FileSystem.get(conf);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        if (fs.exists(new Path(args[1])))
            fs.delete(new Path(args[1]), true);
        job.setMapperClass(Map.class);
        job.setReducerClass(Reduce.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        job.setJarByClass(ReadFile.class);     
        job.waitForCompletion(true);
    }

}

映射器

代码语言:javascript
复制
public class Map extends Mapper<LongWritable, Text, Text, IntWritable> {

    public void setup(Context context) throws IOException{
        Path pt=new Path("hdfs:/path/to/file");//Location of file in HDFS
        FileSystem fs = FileSystem.get(new Configuration());
        BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(pt)));
        String line;
        line=br.readLine();
        while (line != null){
            System.out.println(line);
            line=br.readLine();
        }
    }
    public void map(LongWritable key, Text value, Context context)
            throws IOException, InterruptedException {
      //as your wish
        }
    }
}

上面的代码可以帮助你从HDFS中读取文本文件。

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26209773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档