| | 1 | {{{ |
| | 2 | #!html |
| | 3 | <div style="text-align: center; color:#151B8D"><big style="font-weight: bold;"><big><big> |
| | 4 | HDFS 的檔案系統操作 |
| | 5 | </big></big></big></div> <div style="text-align: center; color:#7E2217"><big style="font-weight: bold;"><big> |
| | 6 | 上傳 |
| | 7 | </big></big></div> |
| | 8 | }}} |
| | 9 | |
| | 10 | [wiki:waue/2011/0426 回課程大綱 << ] 第一關 [wiki:waue/2011/0426_2 > 下一關 ] |
| | 11 | |
| | 12 | = Ex1. 從 local 上傳資料到 hdfs = |
| | 13 | |
| | 14 | * 請在 local 端建立資料: /home/hadoop/input |
| | 15 | * 請檢查 hdfs 無該資料夾: /user/hadoop/program_put_input |
| | 16 | |
| | 17 | {{{ |
| | 18 | #!java |
| | 19 | package itri; |
| | 20 | |
| | 21 | import java.io.IOException; |
| | 22 | |
| | 23 | import org.apache.hadoop.conf.Configuration; |
| | 24 | import org.apache.hadoop.fs.FileSystem; |
| | 25 | import org.apache.hadoop.fs.Path; |
| | 26 | import org.apache.hadoop.util.GenericOptionsParser; |
| | 27 | |
| | 28 | |
| | 29 | public class HdfsUpload { |
| | 30 | // 將檔案從local上傳到 hdfs , src 為 local 的來源, dst 為 hdfs 的目的端 |
| | 31 | static boolean putToHdfs(String src, String dst, Configuration conf) { |
| | 32 | Path dstPath = new Path(dst); |
| | 33 | try { |
| | 34 | // 產生操作hdfs的物件 |
| | 35 | FileSystem hdfs = dstPath.getFileSystem(conf); |
| | 36 | // 上傳 |
| | 37 | hdfs.copyFromLocalFile(false, new Path(src),new Path(dst)); |
| | 38 | |
| | 39 | } catch (IOException e) { |
| | 40 | e.printStackTrace(); |
| | 41 | return false; |
| | 42 | } |
| | 43 | return true; |
| | 44 | } |
| | 45 | static public void main(String argv[]){ |
| | 46 | // String[] argc = { "/tmp/input","program_put_input" }; argv = argc; |
| | 47 | |
| | 48 | Configuration conf = new Configuration(); |
| | 49 | String[] args = new GenericOptionsParser(conf, argv).getRemainingArgs(); |
| | 50 | if (args.length < 2) { |
| | 51 | System.out.println("HdfsUpload <local_path> <hdfs_path>"); |
| | 52 | return; |
| | 53 | } |
| | 54 | |
| | 55 | boolean status = putToHdfs(args[0], args[1], conf); |
| | 56 | System.err.println("Upload? :" + status); |
| | 57 | |
| | 58 | } |
| | 59 | } |
| | 60 | }}} |
| | 61 | |
| | 62 | * 執行後請檢查 hdfs 是否有該資料夾: /user/hadoop/program_put_input |
| | 63 | |