hadoop SequenceFile 读取例程注释

来源:互联网 发布:手机的编程游戏平台 编辑:程序博客网 时间:2024/05/17 07:52
[java] view plaincopy
  1. import java.io.IOException;  
  2. import java.net.URI;  
  3.   
  4. import org.apache.hadoop.conf.Configuration;  
  5. import org.apache.hadoop.fs.FileSystem;  
  6. import org.apache.hadoop.fs.Path;  
  7. import org.apache.hadoop.io.IOUtils;  
  8. import org.apache.hadoop.io.SequenceFile;  
  9. import org.apache.hadoop.io.Writable;  
  10. import org.apache.hadoop.util.ReflectionUtils;  
  11.   
  12. // vv SequenceFileReadDemo  
  13. public class SequenceFileReadDemo {  
  14.     
  15.   public static void main(String[] args) throws IOException {  
  16.     String uri = args[0];  
  17.     Configuration conf = new Configuration();  
  18.     FileSystem fs = FileSystem.get(URI.create(uri), conf);  
  19.     Path path = new Path(uri);  
  20.   
  21.     SequenceFile.Reader reader = null;  
  22.     try {  
  23.       reader = new SequenceFile.Reader(fs, path, conf);//返回 SequenceFile.Reader 对象  
  24.       Writable key = (Writable)  
  25.         ReflectionUtils.newInstance(reader.getKeyClass(), conf);//getKeyClass()获得Sequence中使用的类型  
  26.       Writable value = (Writable)//ReflectionUtils.newInstace 得到常见的键值的实例  
  27.         ReflectionUtils.newInstance(reader.getValueClass(), conf);//同上  
  28.       long position = reader.getPosition();  
  29.       while (reader.next(key, value)) { //next()方法迭代读取记录 直到读完返回false  
  30.         String syncSeen = reader.syncSeen() ? "*" : "";//替换特殊字符 同步  
  31.         System.out.printf("[%s%s]\t%s\t%s\n", position, syncSeen, key, value);  
  32.         position = reader.getPosition(); // beginning of next record  
  33.       }  
  34.     } finally {  
  35.       IOUtils.closeStream(reader);  
  36.     }  
  37.   }  
  38. }  
0 0