使用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),已经上传成功:
二、从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); }
运行后查看本地,已经下载成功,且可以正常打开: