HDFS的java接口

之前,我们学习的都是使用hadoop或hdfs的shell命令传送数据,这样使用不方便。
为此,我们可以使用HDFS的相关java接口,给hadoop里的hdfs传送数据
 
对开发者来说,不用关心内部实现细节。使用Hadoop内部工具类
 1 package cn.itcast.hadoop.hdfs;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.InputStream;
 8 import java.io.OutputStream;
 9 import java.net.URI;
10 import java.net.URISyntaxException;
11 
12 import org.apache.hadoop.conf.Configuration;
13 import org.apache.hadoop.fs.FileSystem;
14 import org.apache.hadoop.fs.Path;
15 import org.apache.hadoop.io.IOUtils;
16 import org.junit.Before;
17 import org.junit.Test;
18 
19 public class HDFSDemo {
20 
21     FileSystem fs = null;
22     
23     @Before
24     public void init() throws IOException, URISyntaxException, InterruptedException
25     {
26         //首先创建FileSystem的实现类(工具类)
27         fs = FileSystem.get(new URI("hdfs://itcast01:9000"), new Configuration(), "root");
28     }
29     
30     @Test
31     public void testUpload() throws Exception
32     {
33         //读取本地文件系统的文件,返回输入流
34         FileInputStream in = new FileInputStream("e://example.jar");
35         //在HDFS上创建一个文件,返回输出流
36         OutputStream out = fs.create(new Path("/test.jar"));
37         //输入->输出
38         IOUtils.copyBytes(in, out, 4096, true);
39     }
40     
41     @Test
42     public void testDownload() throws IllegalArgumentException, IOException
43     {    //下载文件
44         fs.copyToLocalFile(new Path("/jdk1.7"), new Path("d://jkd111"));
45     }
46     @Test
47     public void testMkdir() throws Exception, IOException
48     {    //创建目录
49         boolean mkdirs = fs.mkdirs(new Path("/itcast0106"));
50         System.out.println(mkdirs);
51     }
52     
53     
54     @Test
55     public void testDel() throws Exception
56     {   //删除文件或删除目录
57         boolean flag = fs.delete(new Path("/itcast0106"), true);
58         System.out.println(flag);
59     }
60     
61     public static void main(String[] args) throws IOException, URISyntaxException {
62         // TODO Auto-generated method stub
63         FileSystem fs = FileSystem.get(new URI("hdfs://itcast01:9000"), new Configuration());
64         InputStream in = fs.open(new Path("/jdk1.7"));
65         OutputStream out = new FileOutputStream("d://jkd1.7");
66         IOUtils.copyBytes(in, out, 4096, true);
67     }
68 
69 }

 

posted @ 2017-06-04 19:06  独立小桥风满袖  阅读(382)  评论(0编辑  收藏  举报