在mapper中逐行读取HDFS中的文本文件

以下是Mappers的代码,从HDFS读取文本文件对吗? 如果是:

  1. 如果不同节点中的两个映射器几乎同时尝试打开文件会发生什么?
  2. 是不是需要关闭InputStreamReader ? 如果是这样,如何在不关闭文件系统的情况下执行此操作?

我的代码是:

 Path pt=new Path("hdfs://pathTofile"); FileSystem fs = FileSystem.get(context.getConfiguration()); BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(pt))); String line; line=br.readLine(); while (line != null){ System.out.println(line); 

这将是有效的,有一些修改 – 我假设您粘贴的代码被截断:

 Path pt=new Path("hdfs://pathTofile"); FileSystem fs = FileSystem.get(context.getConfiguration()); BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(pt))); try { String line; line=br.readLine(); while (line != null){ System.out.println(line); // be sure to read the next line otherwise you'll get an infinite loop line = br.readLine(); } } finally { // you should close out the BufferedReader br.close(); } 

您可以使用多个映射器读取同一个文件,但是使用分布式缓存更有意义(不仅减少了承载文件块的数据节点的负载,而且效率更高)如果你的工作任务数量大于任务节点数