java操作hdfs实现上传、下载等功能

使用hadoop提供的接口可以轻松的实现利用java来操作hdfs。

一、如从本地往hdfs上上传个文件:

package hadoop.hdfs;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.Test;
/*
 * 导入hadoop安装包里面的jar包:
 */
public class TestHdfs {
	/*
	 * 相当于hadoop fs -put /root/xing.txt hdfs://node113:9000/xing.txt
	 * 命令往hdfs上放文件一样
	 */
	@Test
	public void testUploadToHdfs() throws Exception{
		FileSystem fs=FileSystem.get(new URI("hdfs://node113:9000"), 
				new Configuration(), "root");
		InputStream in=new FileInputStream("D:\\zhao\\linux2.txt");
		OutputStream out=fs.create(new Path("/local/linux2_hdfs.txt"));
		IOUtils.copyBytes(in, out, 2000, true);
	}
}

运行junit单元测试,发现运行成功,查看hdfs管理界面(http://node113:50070),已经上传成功:

image.png

二、从hdfs上下载文件到本地:

	/*
	 * 相当于hadoop fs -get hdfs://node113:9000/xing.txt /root/haha.txt
	 * 命令从hdfs上下载文件一样
	 */
	@Test
	public void testDownloadFromHdfs() throws Exception{
		FileSystem fs=FileSystem.get(new URI("hdfs://node113:9000"), 
				new Configuration(), "root");
		InputStream in=fs.open(new Path("/local/linux2_hdfs.txt"));
		OutputStream out=new FileOutputStream("d:\\zhao\\linux2_from_hdfs.txt");
		IOUtils.copyBytes(in, out, 2000, true);
	}

运行后查看本地,已经下载成功,且可以正常打开:

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值