2011年4月18日 星期一

Write a file to HDFS

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataOutputStream;

首先 先建立一個FileSystem物件,在建立此物件時,必需傳入一個Configuration object,因此
我們先Create一個Configuration object
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
之後就可以用這個 FileSystem object來開檔,創出一個FSDataOutputStream object
Path outFile = new Path("/tmp/test");
FSDataOutputStream out = fs.create(outFile);

之後就用
out.write(s.getBytes(),0,s.length()); 來寫入要寫的 String s 資訊

最後別忘了把FileSystem關掉 才會正式寫回去
fs.close();


P.S. 在Map或Reduce中 可以用Context.getConfiguration() 取得 Configuration object
但如果這樣,就不能關掉FileSystem,因為FileSystem 還會被MapReduce用到
MapReduce的一個Job跑完就會自動關掉FileSystem 了~


沒有留言:

張貼留言