使用hdfs的api接口分別實現從本地上傳文件到集群和從集群下載文件到本地。
1)上傳文件主要是使用FileSystem類的copyFromLocalFile()方法來實現,另外我們上傳文件時可以指定以多大的物理塊來存儲此文件,使用conf.set("dfs.block.size","8388608")設置物理塊大小是8M,此方法第二個參數的單位是字節。另外編譯此代碼除了需要使用hadoop-core-1.2.1.jar,還需要使用
commons-configuration-1.6.jar包。完整代碼如下:
/** * Created with IntelliJ IDEA. * User: hadoop * Date: 16-3-13 * Time: 下午6:31 * To change this template use File | Settings | File Templates. */ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import java.io.IOException; public class uploadFile { public static void main(String[] args) throws IOException { Configuration conf=new Configuration();//只讀取了core.xml文件 //conf.addResource("hdfs-default.xml"); //Long x=conf.get("dfs.block.size") ; conf.set("dfs.block.size", args[0]);//第二個參數的單位是字節,並且是字符串形式 FileSystem fs=FileSystem.get(conf); Path src=new Path(args[1]);//參數是本地文件的絕對路徑的字符串形式 Path dst=new Path(args[2]); fs.copyFromLocalFile(src,dst); System.out.println("upload to:"+conf.get("fs.default.name")); } }
例如將本地test目錄下的F1k1k文件上傳到集群,所使用的命令就是:
hadoop jar uploadFile.jar uploadFile 8388608 /home/hadoop/test/F1k1k /data0313
2)從集群下載文件類似,只需要將copyFromLocalFile()方法改為copyToLocalFile(),只不過代碼中src變成了集群路徑,dst是本地路徑
如下所示:
1 /** 2 * Created with IntelliJ IDEA. 3 * User: hadoop 4 * Date: 16-3-13 5 * Time: 下午6:31 6 * To change this template use File | Settings | File Templates. 7 */ 8 9 import org.apache.hadoop.conf.Configuration; 10 import org.apache.hadoop.fs.FileSystem; 11 import org.apache.hadoop.fs.Path; 12 13 import java.io.IOException; 14 15 public class uploadFile { 16 17 public static void main(String[] args) throws IOException { 18 Configuration conf=new Configuration(); 19 //conf.addResource("hdfs-default.xml"); 20 //Long x=conf.get("dfs.block.size") ; 21 conf.set("dfs.block.size", args[0]); 22 FileSystem fs=FileSystem.get(conf); 23 Path src=new Path(args[1]);//src是集群路徑 24 Path dst=new Path(args[2]);//dst是本地路徑 25 fs.copyToLocalFile(src,dst); 26 System.out.println("upload to:"+conf.get("fs.default.name")); 27 } 28 }