分布式下读取文件

来源:互联网 发布:发现值得买网站源码 编辑:程序博客网 时间:2024/06/06 08:33
  advertiserFile = context.getConfiguration().get(ADVERTISER_INPUT);
    FileSystem adSystem = FileSystem.get(context.getConfiguration());
    FSDataInputStream fsDataInputStream = adSystem.open(new Path(advertiserFile));
    InputStreamReader inputStreamReader = new InputStreamReader(fsDataInputStream);
    adBuffer = new BufferedReader(inputStreamReader);


    String advertiserLine = "";
    try {
      while ((advertiserLine = adBuffer.readLine()) != null) {
        String[] adInput = advertiserLine.split("\t", 2);
        if (adInput.length < 2) {
          continue;
        }
        advertiserSet.put(adInput[0], adInput[1]);
      }
    } catch (IOException e) {
      LOG.info("Advertiser topic load incorrectly.");

    }


这种方式是分布式读取文件的方式吧,是在分布式系统中读取文件。


但是如果需要将一些文件从本地来读,而不是分布式下的读取方式,此时需要用到DistributedCache 。这个方式是将文件分别拷贝到hadoop的每一台机器的本地上,然后在用时就只用从本地读就行了,不用再从一台机器读,因此此时读的时候可以用Filereader这种本地读取文件的方式了。这个参考一下

1. 在main中先告訴Configuration 哪個File要被當成DistributedCache
DistributedCache.addCacheFile(new URI("$(path in HFS)")
,$(configuration object));
For example:
Configuration conf = new Configuration();
DistributedCache.addCacheFile(new URI("/myDis/test.dat"),conf);

2. 而在 map 或 reduce 中
可以用 DistributedCache.getLocalCacheFiles(context.getConfiguration());
取得CacheFile的Path Array;
For example:
Path[] localFiles;
localFiles = DistributedCache.getLocalCacheFiles(context.getConfiguration());
接下來就是Java的正常開檔了,提供一個用法
FileReader fr = new FileReader(localFiles[0].toString());
BufferedReader br = nre bufferedReader(fr);
String fileline = br.readLine(); //Read first line in the file

如果我們把localFile的Path印出來,我們不難發現,Hadoop 會幫我們把檔案偷偷放在我們在core-site.xml (詳細請參考Hadoop建置文件) 裡設定的hadoop.tmp.dir下的
mapred/local/taskTracker/archive/${ServerName}/${path in HFS}

具体来源:http://kuanyuhadoop.blogspot.com/2011/03/how-to-use-mapreduce-distributedcache.html


这个在用的时候需要注意的是写入的一定是URI的,因此如果是个path,需要转换为URI的格式。这个参考hadoop 

1. Copy the requisite files to the FileSystem:  http://hadoop.apache.org/common/docs/r0.20.1/api/org/apache/hadoop/filecache/DistributedCache.html#getLocalCacheFiles(org.apache.hadoop.conf.Configuration)

另外,在hadoop下,Path类的使用,需要注意path.getname(),和path.toString()是不一样的。因此在用一个类之前要结合hadoop, java两个一起查看,一般情况下要先查找hadoop环境下的类说明http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/fs/Path.html,如果确定是属于java的,再查找sun等的类。



原创粉丝点击