第一步:首先搭建java的编译环境。创建一个Java Project工程,名为upload。
第二步:选中所需的Jar包。
选中JRE System Library 选择BuildPath Configure Build Path 选择hadoop相应的jar包。
通过Add External JARS --〉Hadoop-0.20.2下所有的jar包以及lib下所有的jar包。OK。操作步骤如图:
Hadoop-0.20.2下所有的jar包。
![](https://i-blog.csdnimg.cn/blog_migrate/e6439bcb4ee4f90c4578c908fe412d57.png)
lib下的所有jar包。
![](http://static.oschina.net/uploads/space/2013/0821/223901_TOLE_109481.png)
第三步:创建class 名为UploadFile.
![](https://i-blog.csdnimg.cn/blog_migrate/1dc2e65d39f2ec160fafdc056c1bcde1.png)
第四步:编写代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
package
upload;
import
java.io.BufferedInputStream;
import
java.io.FileInputStream;
import
java.io.InputStream;
import
java.io.OutputStream;
import
java.net.URI;
import
org.apache.hadoop.conf.Configuration;
import
org.apache.hadoop.fs.FileSystem;
import
org.apache.hadoop.fs.Path;
import
org.apache.hadoop.io.IOUtils;
public
class
UploadFile {
public
static
void
main(String[] args) {
try
{
String localStr = args[
0
];
String dst = args[
1
];
//in对应的是本地文件系统的目录
InputStream in =
new
BufferedInputStream(
new
FileInputStream(localStr));
Configuration conf =
new
Configuration();
//获得hadoop系统的连接
FileSystem fs = FileSystem.get(URI.create(dst),conf);
//out对应的是Hadoop文件系统中的目录
OutputStream out = fs.create(
new
Path(dst));
IOUtils.copyBytes(in, out,
4096
,
true
//4096是4k字节
System.out.println(
"success"
);
}
catch
(Exception e) {
System.out.println(e.toString());
}
}
}
|
第五步:在Run Configuration里面设置两个参数,并执行。
点击 Run Configuration
在Java Application中 设置 Project和MainClass
![](http://static.oschina.net/uploads/space/2013/0821/224252_Jtba_109481.png)
Arguments 加两个参数/home/cui/xxxx hdf://cui:9000/xxx
Applay Run
第六步:查看结果。
显示运行成功。
![](http://static.oschina.net/uploads/space/2013/0821/224421_oFh6_109481.png)
在hadoop文件系统中已经看到了hadoop-0.20.2.tar.gz了。
![](http://static.oschina.net/uploads/space/2013/0821/224538_CZ2a_109481.png)
![](http://static.oschina.net/uploads/space/2013/0821/224612_vzqE_109481.png)
至此文件通过代码上传成功!
将代码打包成jar文件,并测试。
1. 在Run Configurations里面命名为uploadfile。
2. 右击工程,执行Export,选择Runnable JAR file。点击下一步。
3. 选择刚才的configuration uploadfile,选择导出路径/home/cui。命名为upload.jar
点击下一步,导出成功。
4. 通过java命令执行。
5. 通过浏览器查看。
upload_hdfs.jar 已经存在。