Big Data

HDFS 파일 특정 부분을 읽어와 로컬 디스크 파일 저장 코드

kogun82 2012. 5. 23. 09:52

입력되는 argument 는 파일명, offset, length 이고 HDFS 에 있는 args[0] 파일에 접근해서 offset 위치에서부터 length 크기만큼의 데이터를 local 에 args[0] 파일명으로 저장하는 코드

public class file_hadoop {

  public static void main(String[] args) throws Exception {
  
    String uri = args[0];
    int buf = 1024 * 1024 * 10;
    int fileNum = 0;
    byte bytearray[] = new byte[buf];
    long offset = Long.parseLong(args[1]);
    long length = Long.parseLong(args[2]);

    int ReadData = 0;
    long ReadSum = 0;

    try {
      Configuration conf = new Configuration();
      FileSystem fs = FileSystem.get(URI.create(uri), conf);

      InputStream in = fs.open(new Path(uri));
      in.skip(offset);

      while (ReadSum < length) {
        if (length - ReadSum < buf)
          buf = (int)(length - ReadSum);

        if ((ReadData = in.read(bytearray, 0, buf)) == -1)
          break;
        IOUtils.copyBytes(new ByteArrayInputStream(bytearray, 0, ReadData), new FileOutputStream(args[0]), buf, false);
        ReadSum += ReadData;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}