1 package com.imooc.bigdata.hadoop.hdfs;
2
3 import org.apache.hadoop.conf.Configuration;
4 import org.apache.hadoop.fs.FSDataOutputStream;
5 import org.apache.hadoop.fs.FileSystem;
6 import org.apache.hadoop.fs.Path;
7 import org.junit.After;
8 import org.junit.Before;
9 import org.junit.Test;
10
11 import java.net.URI;
12
13 /**
14 * 使用Java API操作HDFS文件系统
15 *
16 * 因为是放在test下面,所以最好使用单元测试的方式
17 * 在pom中引入的jUnit单元测试的方式
18 * 单元测试有两个方法:(1)在单元测试之前进行;(2)在单元测试之后进行
19 *
20 * 关键点:
21 * 1)创建Configuration
22 * 2)获取FileSystem
23 * 3)剩下的是HDFS API的操作
24 */
25
26 public class HDFSApp {
27
28 public static final String HDFS_PATH = "hdfs://hadoop000:8020";
29 //Configuration、FileSystem是每一个方法使用之前必须构建的
30 Configuration configuration = null;
31 FileSystem fileSystem = null;
32
33 @Before
34 public void setup() throws Exception{
35 System.out.println("-----setup-----");
36 configuration = new Configuration();
37 configuration.set("dfs.replication", "1");
38 /*
39 *构造一个访问指定HDFS系统的客户端对象
40 * 第一个参数:HDFS的URI
41 * 第二个参数:客户端指定的配置参数
42 * 第三个参数:客户的用户名
43 */
44 fileSystem = FileSystem.get(new URI("hdfs://hadoop000:8020"), configuration, "hadoop");
45 }
46
47 /*
48 * 创建HDFS文件并写入内容
49 */
50 @Test
51 public void create()throws Exception{
52 //FSDataOutputStream out = fileSystem.create(new Path("/hdfsApi/test/t.txt"));
53 FSDataOutputStream out = fileSystem.create(new Path("/hdfsApi/test/x.txt"));
54 out.writeUTF("hello JieQiong Replication 1");
55 out.flush(); //立即将缓冲区的数据输出到接收方
56 out.close();
57 }
58
59 /*
60 *测试文件名更改
61 */
62 @Test
63 public void rename()throws Exception{
64 Path oldPath = new Path("/hdfsApi/test/x.txt");
65 Path newPath = new Path("/hdfsApi/test/y.txt");
66 boolean result = fileSystem.rename(oldPath, newPath);
67 System.out.println(result);
68 }
69
70 @Test
71 public void testReplication(){
72 //get(name, value)
73 System.out.println(configuration.get("dfs.replication"));
74 }
75
76 @After
77 public void tearDown(){
78 System.out.println("-----tearDown-----");
79
80 //置空
81 configuration = null;
82 fileSystem = null;
83 }
84 }
![]()
![]()