如何从Java / Scala中读取Nutch内容?

时间:2014-07-11 13:47:30

标签: java hadoop nutch

我正在使用Nutch抓取一些网站(作为一个独立运行的进程),而我想使用Java(Scala)程序来分析使用Jsoup的网站的HTML数据。

我让Nutch按照tutorial开始工作(没有脚本,只执行单独的指令),我认为它将网站的HTML保存在crawl/segments/<time>/content/part-00000目录中。

问题在于我无法弄清楚如何在Java / Scala程序中实际读取网站数据(URL和HTML)。我读了这个document,但由于我从未使用过Hadoop,所以发现它有点压倒性。

我尝试将示例代码调整到我的环境中,这就是我所得到的(主要是通过guesswprk):

  val reader = new MapFile.Reader(FileSystem.getLocal(new Configuration()), ".../apache-nutch-1.8/crawl/segments/20140711115438/content/part-00000", new Configuration())
  var key = null
  var value = null
  reader.next(key, value) // test for a single value
  println(key)
  println(value)

但是,当我运行它时,我收到了这个异常:

Exception in thread "main" java.lang.NullPointerException
    at org.apache.hadoop.io.SequenceFile$Reader.next(SequenceFile.java:1873)
    at org.apache.hadoop.io.MapFile$Reader.next(MapFile.java:517)

我不知道如何使用MapFile.Reader,具体来说,我应该传递给它的构造函数参数。我应该传递哪些配置对象?这是正确的文件系统吗?那是我感兴趣的数据文件吗?

1 个答案:

答案 0 :(得分:1)

<强> Scala的:

val conf = NutchConfiguration.create()
val fs = FileSystem.get(conf)
val file = new Path(".../part-00000/data")
val reader = new SequenceFile.Reader(fs, file, conf)

val webdata = Stream.continually {
  val key = new Text()
  val content = new Content()
  reader.next(key, content)
  (key, content)
}

println(webdata.head)

<强>爪哇:

public class ContentReader {
    public static void main(String[] args) throws IOException { 
        Configuration conf = NutchConfiguration.create();       
        Options opts = new Options();       
        GenericOptionsParser parser = new GenericOptionsParser(conf, opts, args);       
        String[] remainingArgs = parser.getRemainingArgs();     
        FileSystem fs = FileSystem.get(conf);
        String segment = remainingArgs[0];
        Path file = new Path(segment, Content.DIR_NAME + "/part-00000/data");
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, file, conf);
        Text key = new Text();
        Content content = new Content();
        // Loop through sequence files
        while (reader.next(key, content)) {
            try {
                System.out.write(content.getContent(), 0,
                        content.getContent().length);
            } catch (Exception e) {
            }
        }
    }
}

或者,您可以使用org.apache.nutch.segment.SegmentReaderexample)。