1. 程式人生 > >Hadoop第一個程式,利用API向HDFS中寫入資料

Hadoop第一個程式,利用API向HDFS中寫入資料

這時學習Hadoop以來寫的第一個成功的程式,程式仿照《Hadoop實戰》中的PutMerge程式,這裡有幾個要注意的地方:

1.hdfs的地址是一個網路地址,如下面的:hdfs://localhost:9000/test3

2.確保不會出現“許可權不足”的異常

import java.io.IOException;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
 * 
 */

/**
 * Hadoop版本1.2.1
 * 系統ubuntu 12.04
 * JDK 1.7
 *
 */
public class PutMerge {

	public static void main(String[] args) throws IOException {
		
		Configuration conf = new Configuration();
		
		Path inputDir = new Path("/home/hadoop/input");
		String serverPath = "hdfs://localhost:9000/test3";
		Path hdfsfile = new Path(serverPath);
		
		FileSystem hdfs = FileSystem.get(URI.create(serverPath), conf);
		FileSystem local = FileSystem.getLocal(conf);
		FileStatus[] status = local.listStatus(inputDir);
		FSDataOutputStream out = hdfs.create(hdfsfile);
		
		for(int i = 0; i < status.length; i++) {
			FSDataInputStream in = local.open(status[i].getPath());
			byte buffer[] = new byte[256];
			int byteread = 0;
			while((byteread = in.read(buffer)) > 0) {
				out.write(buffer);
			}
			in.close();
		}
		out.close();
	}

}