我们使用eclipse编程连接hadoop完成在hdfs上面创建文件。
实验代码如下:
public class FileDemo {
`private Configuration conf = new Configuration();`// 这里创建conf对象有一个默认参数,boolean
// loadDefaults,默认为true
private String rootPath = new String("hdfs://192.168.13.129:9000/");
private FileSystem coreSys = null;
/**
* 每次执行之前初始化操作,初始化FileSystem核心对象
*/
public void iniFileSystemObject() {
try {
coreSys = FileSystem.get(URI.create(rootPath), conf);
} catch (IOException e) {
System.out.println("初始化HDFS核心文件对象失败:" + e.getLocalizedMessage());
}
}
/**
* 在HDFS上创建文件
*
* @throws Exception
*/
public void createFile() throws Exception {
Path hdfsPath = new Path(rootPath + "/test/createfile");
// System.out.println(coreSys.getHomeDirectory());
// System.setProperty("hadoop.home.dir",
// "D:/linux/hadoop-2.6.4/hadoop-2.6.4/bin");
String content = "Hello hadoop,this is first time that I create file on hdfs";
FSDataOutputStream fsout = coreSys.create(hdfsPath);
BufferedOutputStream bout = new BufferedOutputStream(fsout);
bout.write(content.getBytes(), 0, content.getBytes().length);
bout.close();
fsout.close();
System.out.println("文件创建完毕!");
}
}
在eclipse上面新建一个map reduce工程。导入jar包。在hadoop中share下面的mapreduce下面的所有jar包都导入到工程中。
下载对应版本的
hadoop.dll,winutils.exe,winutils.pdb三个文件,hadoop.dll,winutils.exe文件放在windows下面hadoop中的bin目录下面,winutils.exe拷贝到c/windows/System32下面。
下面记得配置windows解压后hadoop中bin到环境变量中。完成上面的配置,我们开始讲解上面的代码
private Configuration conf = new Configuration();
private String rootPath = new String("hdfs://192.168.13.129:9000/");
private FileSystem coreSys = null;
创建一个conf,rootPath里面主要设置hdfs的ip地址和端口,地址和端口见linux上面core-site.xml文件夹。
写一个FileSystem用来创建文件和建立文件输出流。
Path hdfsPath = new Path(rootPath + "/test/createfile");
FSDataOutputStream fsout = coreSys.create(hdfsPath);
path主要填写创建文件的位置。
测试代码如下:
public class HdfsTest {
public static void main(String[] args) {
FileDemo filedemo = new FileDemo();
filedemo.iniFileSystemObject();
try {
filedemo.createFile();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
执行完测试代码,我们就可以在DFS Location重新连接后找到新建的文件。