【问题标题】:Hadoop write output into a txt fileHadoop 将输出写入 txt 文件
【发布时间】:2013-07-17 04:48:22
【问题描述】:

我正在考虑如何将 Hadoop 的输出写入 txt 文件,而不是写入 HDFS。 比如我放了如下代码:

    // Create the job specification object
    Job job1 = new Job();
    job1.setJarByClass(Main.class);
    job1.setJobName("Day Measurment");

    // Setup input and output paths
    FileInputFormat.addInputPath(job1, new Path(args[0]));
    FileOutputFormat.setOutputPath(job1, new Path(args[1]));

    // Set the Mapper and Reducer classes
    job1.setMapperClass(DayMapper.class);
    job1.setReducerClass(LogReducer.class);

    // Specify the type of output keys and values
    job1.setOutputKeyClass(Text.class);
    job1.setOutputValueClass(LongWritable.class);

    // Wait for the job to finish before terminating
    job1.waitForCompletion(true);

    PrintWriter pw = new PrintWriter("hadoop.csv");
    pw.println("abc");
    pw.close();

在我测试我的程序后,Hadoop 工作正常,但我只得到 hadoop.csv,里面没有内容。这是一个空文件,里面没有“abc”。

谁能告诉我为什么?或者告诉我如何将输出打印到常规文件(.csv 或 .log)而不是 HDFS?

【问题讨论】:

    标签: java hadoop hdfs


    【解决方案1】:

    默认情况下,创建的 PrintWriter 对象不使用 flush()。要打开它,您可以在创建 PrintWriter 时向构造函数添加第二个参数。

    PrintWriter pw = new PrintWriter(fw,true); 
    

    如果您不想这样做,您应该可以使用flush()-方法来代替

        PrintWriter pw = new PrintWriter("hadoop.csv");
            pw.println("abc");
            pw.flush();    
            pw.close();
    

    使用flush() 将确保任何要写入的数据不会卡在任何内部缓冲区中,而是简单地推送到底层输出流中。

    看看这个:PrintWriter - Java API

    【讨论】:

      【解决方案2】:
              FileWriter fw = new FileWriter("hadoop.csv");
              PrintWriter pw = new PrintWriter(fw);
      
              pw.println("abc");
      
              pw.flush();
              pw.close();
              fw.close();  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-21
        • 2017-04-29
        • 1970-01-01
        • 1970-01-01
        • 2012-07-13
        • 1970-01-01
        • 2014-07-16
        • 1970-01-01
        相关资源
        最近更新 更多