转自:http://freewxy.iteye.com/blog/1102759
在local 端创建文件: /home/hadoop/tmp/program_get_input
程序执行完毕后检查hdfs 有无该文件: /user/hadoop/program_put_input
package PutToHDFS;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
* 在local 端创建文件: /home/hadoop/tmp/program_get_input
程序执行完毕后检查hdfs 有无该文件: /user/hadoop/program_put_input
* @author hadoop
*
*/
public class PutToHdfs {
/**
* 将文件从local上传到hdfs
* @param src local的来源
* @param dst hdfs的目的端
* @param conf hadoop配置类
* @return
*/
static boolean putToHdfs(String src,String dst,Configuration conf){
Path dstPath = new Path(dst);
try{
//获取操作hdfs的FileSystem类
FileSystem hdfs = dstPath.getFileSystem(conf);
//上传
<span style="color: #00ff00;">hdfs.copyFromLocalFile(false, new Path(src),new Path(dst));</span>
}catch(IOException e){
e.printStackTrace();
return false;
}
return true;
}
/**
*
* @param args
*/
public static void main(String[] args) {
Configuration conf = new Configuration();
String src = "/home/hadoop/tmp/program_get_input";
String dst = "/user/hadoop/program_put_input";
boolean status = putToHdfs(src,dst,conf);
System.err.println("Create?:"+status);
}
}
1、将该java代码打包为HelloHadoop.jar
2、将HelloHadoop.jar从workspace复制到/usr/local/hadoop目录下(你自己的hadoop目录下)
3、运行hadoop框架(伪分布式): $ bin/start-all.sh
4、运行HelloHadoop.jar : $bin/hadoop jar HelloHadoop.jar
5、查看运行结果: $ bin/hadoop dfs -ls