1. 程式人生 > 其它 >使用Java API之檔案重新命名

使用Java API之檔案重新命名

 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 }