您的位置:首页 > 运维架构

Hadoop读写Hdfs系统文件

2011-05-03 11:03 218 查看
Hadoop读写Hdfs系统文件

第一,在程序添加相关引用。
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;

第二,读取文件。
FileSystem hdfs = FileSystem.get(conf);
Path inPath = new Path("/user/asr/in-temp");
//
FSDataInputStream dis = hdfs.open(inPath);
FileStatus stat = hdfs.getFileStatus(inPath);
//
byte[] buffer = new byte[Integer.parseInt(String.valueOf(stat.getLen()))];
dis.readFully(0, buffer);
String str= Bytes.toString(buffer);

第三,写出文件。
FSDataOutputStream dos = hdfs.create(tmpPath1);
String utf8 = "UTF-8";
//
dos.write("/r/n".getBytes(utf8));
dos.write("//ceshi//".getBytes(utf8));
dos.write("/r/n".getBytes(utf8));
Date dat = new Date();
dos.write(dat.toString().getBytes());
dos.close();

第四,可以在map和reduce的方法中使用,在datanode节点执行;
也可以在main方法中执行,在namenode节点执行。
但是在main方法执行的时候,本机调试的时候,需要把FileSystem.getLocal(conf);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: