java操作hdfs

来源:互联网 发布:2015年京东双十一数据 编辑:程序博客网 时间:2024/05/16 04:03

eclipse中创建一个java工程,然后导入hadoop中的7jar(如图);如果为了方便调试hadoop源码,可以关联到hadoop的源码。



引入hadoop安装包中的7jar



关联hadoop源码:



1、使用URL的方式读取hdfs中的数据,这种方式和使用浏览器查看hdfs中的数据一样;缺点是只能读取,不能上传、删除等:

public static finalString HADOOP_PATH = "hdfs://centos1:9000/hello";

public static voidmain(String[] args) throws Exception {

//默认URL只识别http的协议,所以对于hdfs协议需要添加一个解析器

URL.setURLStreamHandlerFactory(newFsUrlStreamHandlerFactory());

URLurl = new URL(HADOOP_PATH);

InputStream  in = url.openStream();

 

/**

 * in 输入流

 * out 输出流

 * buffersize 缓冲区大小

 * close 是否关闭

 */

IOUtils.copyBytes(in,System.out, 1024, true);

}

 

2、使用hadoop提供的FileSystem类,可以全方位操作hdfs中的数据,和hdfs提供的shell一样:

public static finalString HADOOP_PATH = "hdfs://centos1:9000/";

public static finalString DIR_PATH = "/liuxiao";

public static finalString FILE_PATH = "/liuxiao/liuxiao.log";

public static voidmain(String[] args) throws Exception {

Configurationconf = new Configuration();

FileSystemfs = FileSystem.get(new URI(HADOOP_PATH), conf);

 

//创建

fs.mkdirs(newPath(DIR_PATH));

 

//上传

FSDataOutputStreamout = fs.create(new Path(FILE_PATH));

FileInputStreamin = new FileInputStream("F:/liuxiao.log");

IOUtils.copyBytes(in,out, 1024, true);

 

//下载

FSDataInputStream in1 = fs.open(new Path(FILE_PATH));

IOUtils.copyBytes(in1, System.out, 1024, true);

 

//删除

fs.delete(newPath(FILE_PATH), true);

 

}


0 0